I want to use Unity as an IoC besides the UnitOfWork and Repository patterns. I read various related articles and questions but none of them satisfied me completely. I have a problem with all approaches. An example would explain better my problem:

We want to work with two repositories at two separate classes (maybe the business services) but the overall works are in a unit.

Start point is the LocalService1.Method1 method.

public class LocalService1
{
    public void Method1(int id)
    {
        var repository1 = Container.Current.Resolve<IRepository1>(); // Injects the IUnitOfWork for the repository.
        var entity1 = repository1.GetEntity1(id);
        var service2 = Container.Current.Resolve<LocalService2>(); // Maybe it’s better not to use IoC for business logic. This is not my issue.
        service2.Method2(entity1)
    }
}
...
public class LocalService2
{
    public void Method2(Entity1 entity1)
    {
        var repository2 = Container.Current.Resolve<IRepository2>(); // Injects the IUnitOfWork for the repository.
        var count = repository2.GetEntity2sCount(entity1.Id);
        // Do some works with count and entity1
    }
}

The main question is that “How can I share the UnitOfWork (here can be ObjectContext) between the IRepository1 and IRepsitory2 while calling the LocalService1.Method1?”. More important thing is that “I want to be sure about UnitOfWork disposal”.

I guess the answers would focus on these issues:

  • IoC configuration
  • Life Time configuration
  • Disposal time (How and when?)

If you recommend using “HttpContext” please consider about non-web environments.

I know my question is almost about the “Life time management” but I’m looking for an exhaustive approach.

有帮助吗?

解决方案

First: Don't use Unity as a ServiceLocator. This is considered an anti-pattern. Use constructor injection instead.

Unity's LifetimeManagers don't clean up after themselves. This feature is on the wish list for Unity vNext.

If you want your objects to be disposed you should create your own LifetimeManager and a related BuilderStrategy that do clean up.

There is a sample in the TecX project (inside TecX.Unity.Lifetime) which is taken from Mark Seemann's book Dependency Injection in .NET.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top