2016-07-25 122 views
0

我的项目中有一个autofac DI。 我想通过常规公开一个接口,我的项目的所有其他接口将继承。是否可以在启动级别自动注册继承接口的组件?例如:如何在Autofac中注册传统接口

Public interface IConvetionInterface {} 
public interface IImplementationA:IConvetionInterface 
{ 
public void DoSomethingA(); 
} 

public interface IImplementationB:IConvetionInterface 
{ 
public void DoSomethingB(); 
} 

通过构造函数注入;

public class ConsumerA 
    { 
     private readonly IImplementationA _a; 

     public DealerRepository(IImplementationA A) 
     { 
      _a= A; 
     } 

     public Act() 
     { 
      _a.DoSomethingA(); 


     } 

    } 

如何注册IConvetionInterface,使在Autofac所有依赖的决心。

+0

你是什么意思的自动,没有做任何事情像注册应用程序启动组件? – Prashant

+0

谢谢Prashant。这是我问的问题。我们如何在启动级别注册这样的接口及其依赖关系? – vicosoft

+0

你发现的是任何DI容器或autofac的方式,认为你根本不想在应用程序启动时注册,好的你找到了解决方案的快乐编码。 – Prashant

回答

0

我已经能够通过使用autofac大会扫描配置想出这个解决方案在他们的文档页面提供Autofac Documentation Page

我有一个开放的通用接口

public interface IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> 
    { } 

通过

public class Repository<TEntity, TPrimaryKey> : RepositoryBase<TEntity, TPrimaryKey> 
     where TEntity : class, IEntity<TPrimaryKey>{} 
实现

然后,我创建了一个空接口

public interface IConventionDependency 
    { 

    } 

这种方法被称为在启动电平登记自己的组件:

public static void RegisterAPSComponents(ContainerBuilder builder) 
     { 
      builder.RegisterType<APSContext>().InstancePerRequest(); 
      builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)).InstancePerLifetimeScope(); 




    builder.RegisterAssemblyTypes(typeof(IConventionDependency).Assembly).AssignableTo<IConventionDependency>().As<IConventionDependency>().AsImplementedInterfaces().AsSelf().InstancePerLifetimeScope(); 



     } 

通过上述登记,该继承IConventionDependency将在容器中自动注册的任何接口。

例如: 创建一个接口:

public interface IDealerRepository : IConventionDependency 
    { 
     List<Dealers> GetDealers(); 
    } 

然后实现接口:

public class DealerRepository : IDealerRepository 
    { 
     private readonly IRepository<VTBDealer, int> _repository; 

     public DealerRepository(IRepository<VTBDealer, int> repository) 
     { 
      _repository = repository; 
     } 

     public List<Dealers> GetDealers() 
     { 
      return _repository.GetAllList().MapTo<List<Dealers>>(); 


     } 

    } 
总之

,但没有明确登记IDealerRepository,它MVC的控制器构造得到解决。