C#Unity依赖注入不会解析同一个对象,但会创建新对象

时间:2017-02-26 13:05:54

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

我正在向我的控制器注入一项服务,而我手动解析同一服务,但这两项服务并不相同。手动创建的服务正在处理,但自动解析的服务没有处理。让我按代码展示。

这是控制器,有一个IFirmService自动解析,我在测试功能中手动解析了其他IFirmService。这里出现问题,有两个IFirmService由单位解决,但它们不一样。

public class TestmeController : ApiController
{
    IFirmService FirmServiceHeader;
    public TestmeController(IFirmService _FirmServiceHeader)
    {
        //here is successfully resolved FirmService by unity resolver.
        this.FirmServiceHeader = _FirmServiceHeader;
    }

    [Route("api/test")]
    public IHttpActionResult test() {
        //Here is I'm resolving an other service manually.
        IFirmService FirmServiceLocal = this.Configuration.DependencyResolver.GetService(typeof(IFirmService)) as IFirmService;

        if (Object.ReferenceEquals(FirmServiceLocal,FirmServiceHeader)) {
            //Here is the problem, FirmServiceLocal and firmServiceHeader is not resolved as the same
        }

    }
}

WebApiConfig.cs 我将默认的DependencyResolver设置为Unity并设置已注册的类型。

public static class WebApiConfig
{   
    public static void Register(HttpConfiguration config)
    {
        .....
        UnityContainr container = new UnityContainer();
        container.RegisterType<IFirmService, FirmService>(new HierarchicalLifetimeManager());
        //setting the dependency resolver.
        config.DependencyResolver = new UnityResolver(container);
        .....
    }
}

我没有在这里写IFirmService和FirmService类,它是一个一次性类。

概要;我想在test()函数中解析相同的Firmservice。我想在每次web api请求后自动处理它。

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

如果你想要相同的对象,你应该从同一个容器(UnityContainer)获得。

msdn说HierarchicalLifetimeManager:

&#34;区别在于,当存在子容器时,每个子容器都会解析其自己的对象实例,而不与父容器共享一个。在父级解析时,行为就像容器控制的生命周期;在解析父级和子级时,您有不同的实例,每个实例都充当容器控制的生命周期。如果您有多个孩子,每个孩子都会解析自己的实例。&#34;

Configuration.DependencyResolver的容器是root容器。但是controller constructere resolvers container是root容器的子容器。

    IService _service;
    IUnityContainer _container;

    public DefaultController(IService service,IUnityContainer container)
    {
        _service = service;
        _container = container;
    }

enter image description here

所以..你可以从注入的容器中获取相同的对象..

    IService _service;
    IUnityContainer _container;

    public DefaultController(IService service,IUnityContainer container)
    {
        _service = service;
        _container = container;
    }

    [HttpGet]
    public async Task<ResponseObject> Test()
    {
        var localService = _container.Resolve<IService>();
        if (Object.ReferenceEquals(_service, localService))
            Debug.WriteLine("Equal");
        else
            Debug.WriteLine("Not Equal");
    }