2016-09-19 51 views
0

我使用最新的Autofac并想注册同类型和接口两次基于不同的构造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(); 
+0

我认为你的问题应该是如何注册类型的参数。你应该选择一个构造函数。如果您想使用多个工厂类并在您的班级旁边注册工厂。 –

+0

http://autofac.readthedocs.io/en/latest/faq/select-by-context.html –

回答

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

相关问题