If the UnitOfWork
logic is common then the easiest solution is to make UnitOfWork
generic
interface IUnitOfWork<TContext> where TContext: IDbContext { }
public class UnitOfWork<TContext> : IUnitOfWork<TContext>
where TContext : IDbContext
{
private readonly TContext context;
public UnitOfWork(TContext context)
{
this.context = context;
}
}
Then, using the following syntax to register the UnitOfWork
and the IDbContext
's
ObjectFactory.Configure(x =>
{
x.For(typeof(IUnitOfWork<>)).Use(typeof(UnitOfWork<>));
});
You can control which IDbContext
is injected into the UnitOfWork
public LoginController(IUnitOfWork<SecurityContext> securityContextUow) { }
public SalaryController(IUnitOfWork<HrContext> hrContextUow) { }
Here's a quick unit test to prove it works as expected
public class TestUnitOfWork<TContext> : IUnitOfWork<TContext>
where TContext : IDbContext
{
public TContext context { get; set; }
public TestUnitOfWork(TContext context)
{
this.context = context;
}
}
[Test]
public void GetCorrectUnitOfWork()
{
ObjectFactory.Configure(x =>
{
x.For(typeof(IUnitOfWork<>)).Use(typeof(TestUnitOfWork<>));
});
//ObjectFactory.AssertConfigurationIsValid();
var securityContextUow = ObjectFactory
.GetInstance<IUnitOfWork<SecurityContext>>();
var hrContextUow = ObjectFactory
.GetInstance<IUnitOfWork<HrContext>>();
Assert
.That((securityContextUow as TestUnitOfWork<SecurityContext>).context,
Is.InstanceOf<SecurityContext>());
Assert
.That((hrContextUow as TestUnitOfWork<HrContext>).context,
Is.InstanceOf<HrContext>());
}