Check if a simple injector is registered

How can I archive automatic registrations but ignore any types already registered? I am referencing 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

  • SampleRepository is in assembly "MyComp.MyProd.BL.SqlRepositories"
  • OverrideSampleRepository is in another

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

      

+3


source to share


2 answers


The documentation describes 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>();

      



However, read the documentation carefully.

+4


source


You can check registration by doing this



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

      

+1


source







All Articles