I am a little confused about how this would work with Unity. Let's assume the following scenario, I have a controller called TestController that depends upon two Services ServiceA and ServiceB. Now serviceA depends upon two Repositories, RepositoryA1 and RepositoryA2. ServiceB depends upon one Repository, RepositoryB. Let's further assume that ServiceA, RepositoryA1 and RepositoryA2 depends upon UnitOfWork, UnitOfWork1. I am having trouble understanding how to implement this for MVC3 and the Unity Application Block. Could someone provide an example of how this should be coded?
There's a lot opinions on this but this is how I worked it out for myself
UnitOfWork
public interface IUnitOfWork : IDisposable
{
FooContext DbContext { get; }
void Save();
}
public class UnitOfWork : IUnitOfWork
{
protected string ConnectionString;
private FooContext context;
public UnitOfWork(string connectionString)
{
this.ConnectionString = connectionString;
}
public FooContext DbContext
{
get
{
if (context == null)
{
context = new FooContext(ConnectionString);
}
return context;
}
}
...
}
GenericRepository
public class GenericRepository<TEntity> :
IGenericRepository<TEntity> where TEntity : class
{
protected FooContext DbContext;
public GenericRepository(IUnitOfWork unitOfWork)
{
this.DbContext = unitOfWork.DbContext;
}
...
}
Generic repositories here but they could just as well be built to be specific.
Service
public class FooService : IFooService
{
private IUnitOfWork unitOfWork;
private IGenericRepository<Foo> fooRepository;
private IGenericRepository<Bar> barRepository;
public FooService(IUnitOfWork unitOfWork,
IGenericRepository<Foo> fooRepository,
IGenericRepository<Bar> barRepository)
{
this.unitOfWork = unitOfWork;
this.fooRepository = fooRepository;
this.barRepository = barRepository;
}
}
You still need to pass the IUnitOfWork to get access to the Save method. I suppose I could have gotten it from one of the repositories.
UnityConfig
var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(),
new InjectionConstructor(ConnectionString));
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<IFooService, FooService>();
container.RegisterType<IBarService, BarService>();
Controller
private IFooService fooService;
private IBarSevice barService;
public HomeController(IFooService fooService, IBarService barService)
{
this.fooService = fooService;
this.barService = barService;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With