简体   繁体   中英

How to resolve nested dependenies with Unity?

how can I config my unity container in order resolving a tree of depended objects?? assume we have some class like this:

    public class Foo : IFoo
    {
        [Dependency]
        public IBar Bar { get; set; }
    }

    public class Bar : IBar
    {
        [Dependency]
        public IRepository Repository { get; set; }
    }

    public class Repository : IRepository
    {
        [Dependency]
        public IService Service { get; set; }
    }

and I want resolve the Foo: Container.ResolveAll();

is it possible to resolve an unlimited nested depended objects?

Building up trees of dependencies (dependency graphs) is what DI libraries are built for.

Best practice is to use constructor injection instead of property injection. This also removes the need to let your classes know anything about your DI library.

So step one is to refactor to constructor injection as follows:

public class Foo : IFoo
{
    private readonly IBar bar;
    public Foo (IBar bar) {
        this.bar = bar;
    }
}

public class Bar : IBar
{
    private readonly IRepository repository;        
    public Bar(IRepository repository) {
        this.repository = repository;
    }
}

public class Repository : IRepository
{
    private readonly IService service;        
    public Repository(IService service) {
        this.service = service;
    }
}

Step two is to configure the container:

var container = new UnityContainer();

container.RegisterType<IFoo, Foo>();
container.RegisterType<IBar, Bar>();
container.RegisterType<IRepository, Repository>();
container.RegisterType<IService, Service>();

Step three is to resolve IFoo :

IFoo foo = container.Resolve<IFoo>();

Now Unity will resolve the whole object graph for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM