如何在 autofac 中使用构造函数注册模块?

How do I register modules with constructors in autofac?

如何在 autofac 中使用构造函数注册模块?

我有以下模块:

public class MediatRModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterMediatR(typeof(ApplicationAssemblyMarker).Assembly);
    }
}

public class PersistenceModule : Module
{
    public string ConnectionString { get; }

    public PersistenceModule(string connectionString)
    {
        if (string.IsNullOrWhiteSpace(connectionString))
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(connectionString));

        ConnectionString = connectionString;
    }

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<SqlConnectionFactory>()
            .As<ISqlConnectionFactory>()
            .WithParameter("connectionString", ConnectionString)
            .InstancePerLifetimeScope();

        builder
            .RegisterGeneric(typeof(AsyncRepository<>))
            .As(typeof(IAsyncRepository<>))
            .InstancePerLifetimeScope();
    }
}

PersistenceModule 它包含一个构造函数,我无法在启动方法中通过 RegisterAssemblyModules 注册所有模块。

    public void ConfigureContainer(ContainerBuilder containerBuilder)
    {
        containerBuilder
            .RegisterModule(new PersistenceModule(Configuration.GetConnectionString("DefaultConnection")));

        containerBuilder
            .RegisterModule(new DomainModule());

        containerBuilder
            .RegisterModule(new MediatRModule());

        containerBuilder
            .RegisterModule(new CommandsModule());

        containerBuilder
            .RegisterModule(new QueriesModule());
    }

如果模块采用构造函数参数,则无法自动注册它。您必须直接在注册中提供值。

您的 Module 构造函数中不能有依赖项。但是您可以通过从容器中解析来为参数提供一个值:

builder.RegisterType<SqlConnectionFactory>()
    .As<ISqlConnectionFactory>()
    .WithParameter(
        // match parameter
        (info, context) => info.Name == "connectionString",

        // resolve value
        (info, context) =>
        {
            var config = context.Resolve<Microsoft.Extensions.Configuration.IConfiguration>();
            return config.GetConnectionString("DefaultConnection");
        }
    );

参考资料