我对Unity如何使用有点困惑。让我们假设以下场景,我有一个名为TestController的控制器,它依赖于两个Services ServiceA和ServiceB。现在serviceA依赖于两个存储库,RepositoryA1和RepositoryA2。 ServiceB依赖于一个Repository,RepositoryB。让我们进一步假设ServiceA,RepositoryA1和RepositoryA2依赖于UnitOfWork,UnitOfWork1。我无法理解如何为MVC3和Unity应用程序块实现此功能。有人可以提供一个如何编码的例子吗?
答案 0 :(得分:4)
对此有很多意见,但这就是我为自己解决的问题
<强>的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;
}
...
}
这里的通用存储库,但它们也可以构建为具体的。
<强>服务强>
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;
}
}
您仍需要传递IUnitOfWork才能访问Save
方法。我想我可以从其中一个存储库中获取它。
<强> 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>();
<强>控制器强>
private IFooService fooService;
private IBarSevice barService;
public HomeController(IFooService fooService, IBarService barService)
{
this.fooService = fooService;
this.barService = barService;
}