Simple Injector + UoW + DDD + Multiple Contexts + Entity Framework

8

I need to know how to apply IoC for two contexts.

The scenario is as follows:

I have a Layer called Core (allocates classes that I can reuse in other layers), where I put the interface of IDbContext, IUnitOfWork and UnitOfWork (among other classes that do not are giving me problems for now).

I have two contexts ( AdministrativeDBContext and FinancialDBContext ) separated in different layers with their respective DbSet , since I do not need to expose some tables for unrelated contexts.

Unit of Work:

public class UnitOfWork : IUnitOfWork
{

    private readonly IDbContext _dbContext;

    public UnitOfWork(IDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    //... restante da classe...

}

So, I need to implement the separate IoC in their respective separate contexts:

Administrative Infrastructure Layer:

public class AdministrativoBootstrap 
{
    public static void RegisterServices(Container container)
    {
        container.RegisterPerWebRequest<IDbContext, AdministrativoDbContext>();
        container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
    }
}

Financial Infrastructure Layer:

public class FinanceiroBootstrap 
{
    public static void RegisterServices(Container container)
    {
        container.RegisterPerWebRequest<IDbContext, FinanceiroDbContext>();
        container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
    }
}

After configuring, I initialize them in the Application (MVC):

public class SimpleInjectorInitializer
{
    public static void Initialize()
    {
          InitializeContainer(container);  
          container.Verify();
    }
}


private static void InitializeContainer(Container container)
{
    AdministrativoBootstrap.RegisterServices(container);
    FinanceiroBootstrap.RegisterServices(container);
}

This triggers an "ambiguous relationship" error, where there can not be two classes implementing the same interface (IDbContext).

I used this option inside the initializer:

container.Options.AllowOverridingRegistrations = true;

However, when I see the object in Debug, it does not have the DbSet of the first context (AdministrativeDbContexts), because it has overwritten, since it sequentially calls the FinanceiroBootstrap.RegisterServices (container); / p>

I believe the problem is that you use the same Unit of Work, but in this question someone answers that there can only be one.

Who can help me thank you immensely.

    
asked by anonymous 03.12.2016 / 20:58

1 answer

1

One solution to your problem would be to create an interface and a UnitOfWork class for each context. In this way, it eliminates the ambiguous relationship problem. In case of mapping the context classes, you can omit the reference to the IDbContext interface, the code would look like this:

container.RegisterPerWebRequest<AdministrativoDbContext>();

and

container.RegisterPerWebRequest<FinanceiroDbContext>();
    
02.03.2017 / 03:10