[英]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");
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.