Search code examples
c#simple-injector

Check whether or not Simple injector has registered type


How can I archive automatic registration but ignore any types have already been registered? I reference the code in Simple Injector documentation

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);
}

For example, I have inteface ISampleRepository and there are 2 implementations in different assemblies

  1. SampleRepository is in assembly "MyComp.MyProd.BL.SqlRepositories"
  2. OverrideSampleRepository is in different one

Project 1: worked

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

Project 2: exception because ISampleRepository has already registered

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

Solution

  • The documentation described how to override existing registrations. The documentation contains the following example:

    var container = new Container();
    
    container.Options.AllowOverridingRegistrations = true;
    
    // Register IUserService.
    container.Register<IUserService, FakeUserService>();
    
    // Replaces the previous registration
    container.Register<IUserService, RealUserService>();
    

    Do however read the documentation carefully.