Autofac使用不同的构造函数注册相同的接口

时间:2016-09-19 22:47:52

标签: c# autofac autofac-configuration

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

1 个答案:

答案 0 :(得分: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();

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