1
Vote

Multiple Bounded Contexts IOC DI with UOW

description

Is anyone using this URF project in DDD or across Bounded Contexts?

Extending the IOC instructions hinted at here:
https://blog.longle.io/2013/07/30/bounded-dbcontext-with-generic-unit-of-work-generic-repositories-entity-framework-6-unity-3-0-in-mvc-4/

To allow multiple bounded DataContexts that are configured at AppStartup, there is an implied solution to have a GrandContext that defines all relationships in all EF Entities/Tables and use IOC DI to inject that into repository factory. Yes, this would work, but if you'd like to not maintain and include a 3rd DataContext 'GrandContext', then read on.

As each Entity in each DataContext's Model has a Repository, then during AppStart for IoC, each Repository will now need to inject a UnitOfWork that takes the specific DataContext for that Model.

Inspired by: Daniel J.G., but using the URF and autoFac:
builder.RegisterType<dbContext1>()
    .As<IDataContextAsync>()
    .AsSelf()
    .InstancePerRequest()
    ;

builder.Register(c => new RepositoryProvider(new RepositoryFactories())).As<IRepositoryProvider>();
builder.Register(c => new UnitOfWork(
            c.Resolve<dbContext1>(),
            c.Resolve<IRepositoryProvider>()
        )
    )
    .As<IUnitOfWorkAsync>().InstancePerRequest();

builder.Register(c =>
    new dbContext2())
    .Named<IDataContextAsync>("dbContext2").InstancePerRequest();
builder.RegisterType<dbContext2>()
    .WithParameter(
        (p, c) => p.Name == "dbContext2",
        (p, c) => c.ResolveNamed<IDataContextAsync>("dbContext2")
    );

builder.Register(c => new UnitOfWork(
        c.Resolve<dbContext2>(),
        c.Resolve<IRepositoryProvider>()
        )
    )
    .Named<IUnitOfWorkAsync>("uowBankfeed").InstancePerRequest();

builder.Register
    (c => new Repository<efEntityOne>
        (c.Resolve<dbContext2>(),
        c.Resolve<IUnitOfWorkAsync>)
    ).As<IRepositoryAsync<efEntityOne>>().InstancePerRequest(); 

comments