检查简单进样器是否已注册类型

时间:2017-05-16 10:13:57

标签: c# simple-injector

如何归档自动注册但忽略已注册的任何类型?我在Simple Injector文档中引用了代码

var repositoryAssembly = typeof(SqlUserRepository).Assembly;

var registrations =
    from type in repositoryAssembly.GetExportedTypes()
    where type.Namespace == "MyComp.MyProd.BL.SqlRepositories"
    where type.GetInterfaces().Any()
    select new 
    { 
        Service = type.GetInterfaces().Single(), 
        Implementation = type 
    };

foreach (var reg in registrations) 
{
    // TODO: how to check reg.Service has already registered or not
    container.Register(reg.Service, reg.Implementation, Lifestyle.Transient);
}

例如,我有inteface ISampleRepository,并且在不同的程序集中有2个实现

  1. SampleRepository在程序集“MyComp.MyProd.BL.SqlRepositories”
  2. OverrideSampleRepository位于不同的
  3. 项目1:工作

    var container = new Container();
    container.AutoRegistration();
    

    项目2:异常,因为ISampleRepository已经注册

    var container = new Container();
    container.Register<ISampleRepository, OverrideSampleRepository>();
    container.AutoRegistration(); 
    

2 个答案:

答案 0 :(得分:4)

文档described如何覆盖现有注册。该文档包含以下示例:

var container = new Container();

container.Options.AllowOverridingRegistrations = true;

// Register IUserService.
container.Register<IUserService, FakeUserService>();

// Replaces the previous registration
container.Register<IUserService, RealUserService>();

然而,请仔细阅读文档。

答案 1 :(得分:1)

你应该能够通过这样做来检查注册

container.Verify();
container.GetRegistration(reg.Service) != null; // Not registered