0

我正在使用最新的 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();
4

1 回答 1

0

这似乎可行,但不相信这是最好的。我为 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();

这有效,但同样,这是正确的方法吗?谢谢

于 2016-09-20T01:07:03.850 回答