当服务层依赖于存储库和UnitOfWork时,如何将服务层注入控制器

时间:2013-06-04 01:54:36

标签: asp.net-mvc-3 dependency-injection unity-container

我对Unity如何使用有点困惑。让我们假设以下场景,我有一个名为TestController的控制器,它依赖于两个Services ServiceA和ServiceB。现在serviceA依赖于两个存储库,RepositoryA1和RepositoryA2。 ServiceB依赖于一个Repository,RepositoryB。让我们进一步假设ServiceA,RepositoryA1和RepositoryA2依赖于UnitOfWork,UnitOfWork1。我无法理解如何为MVC3和Unity应用程序块实现此功能。有人可以提供一个如何编码的例子吗?

1 个答案:

答案 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;
}