我正在使用最新的 Autofac 并且想根据不同的构造函数注册两次相同的类型和接口
我的班级/界面
public partial class MyDbContext : System.Data.Entity.DbContext, IMyDbContext
{
public MyDbContext(string connectionString)
: base(connectionString)
{
InitializePartial();
}
public MyDbContext(string connectionString, bool proxyCreationEnabled, bool lazyLoadingEnabled, bool autoDetectChangesEnabled)
: base(connectionString)
{
this.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
this.Configuration.LazyLoadingEnabled = lazyLoadingEnabled;
this.Configuration.AutoDetectChangesEnabled = autoDetectChangesEnabled;
InitializePartial();
}
}
在我的 autofac 设置中,我通过 .. 注册
builder.RegisterType<MyDbContext>().As<IMyDbContext>()
.WithParameter((pi, c) => pi.Name == "connectionString", (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.InstancePerLifetimeScope();
如何使用 Autofac 注册第二个构造函数,以便我可以通过构造函数注入在不同的类上使用它?我在想类似以下的事情,但是 Autofac 如何知道要注入哪个类。
//builder.RegisterType<MyDbContext>().As<IMyDbContext>()
// .WithParameter((pi, c) => pi.Name == "connectionString", (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
// .WithParameter((pi, c) => pi.Name == "proxyCreationEnabled", (pi, c) => false)
// .WithParameter((pi, c) => pi.Name == "lazyLoadingEnabled", (pi, c) => false)
// .WithParameter((pi, c) => pi.Name == "autoDetectChangesEnabled", (pi, c) => false)
// .Named<MyDbContext>("MyDbContextReadOnly")
// .InstancePerLifetimeScope();