Autofac用不同的构造函数注册相同的接口
本文关键字:接口 注册 构造函数 Autofac | 更新日期: 2023-09-27 18:07:51
我正在使用最新的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();
}
}
在我的自动设置我注册通过…
builder.RegisterType<MyDbContext>().As<IMyDbContext>()
.WithParameter((pi, c) => pi.Name == "connectionString", (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.InstancePerLifetimeScope();
我如何注册第二个构造函数,与autoface,以便我可以使用它通过构造函数注入在不同的类?我在想类似下面的东西,但是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();
这似乎有效,但不确定这是最好的可能。我为MyDbContextReadonly类创建了新的IMyDbContextReadonly接口,该接口具有我想使用的构造函数。
public interface IMyDbContextReadonly : IMyDbContext { }
public class MyDbContextReadonly : MyDbContext, IMyDbContextReadonly
{
public MyDbContextReadonly(string connectionString, bool proxyCreationEnabled, bool lazyLoadingEnabled, bool autoDetectChangesEnabled)
: base(connectionString)
{
this.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
this.Configuration.LazyLoadingEnabled = lazyLoadingEnabled;
this.Configuration.AutoDetectChangesEnabled = autoDetectChangesEnabled;
}
}
然后在Autofac配置中我注册了…
builder.RegisterType<MyDbContextReadonly>().As<IMyDbContextReadonly>()
.WithParameter((pi, c) => pi.Name == "connectionString", (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.WithParameter("proxyCreationEnabled", false)
.WithParameter("lazyLoadingEnabled", false)
.WithParameter("autoDetectChangesEnabled", false)
.InstancePerLifetimeScope();
这是有效的,但是,这是正确的方法吗?thx