0

Currently I am using Unity 3.x as my IoC. I also using the Unity.MVC4 library to help manage the lifetime of my resolver. Here is what my resolver looks like:

namespace Wfm.Core.Common.Mvc.Unity
{
    public class WfmDependencyResolver : UnityDependencyResolver
    {
        public WfmDependencyResolver(IUnityContainer container) : base(container)
        {
        }


        private static WfmDependencyResolver _wfmGrabbrResolver;


        public static WfmDependencyResolver Instance { get { return _wfmGrabbrResolver ?? (_wfmGrabbrResolver = new WfmDependencyResolver(InstanceLocator.Instance.Container)); } }
    }
}

The UnityDependencyResolver comes from the Unity.MVC4 library. In my Globabl.asax.cs file I am setting the resolver like this:

DependencyResolver.SetResolver(WfmDependencyResolver.Instance);

Here is my singleton InstanceLocator class:

public class InstanceLocator
    {
        private static InstanceLocator _instance;
        public IUnityContainer Container { get; private set; }

        private InstanceLocator()
        {
            Container = new UnityContainer();

        }

        public static InstanceLocator Instance
        {
            get { return _instance ?? (_instance = new InstanceLocator()); }
        }

        public T Resolve<T>()
        {
            try
            {
                return WfmDependencyResolver.Instance.GetService<T>();
            }
            catch(Exception ex)
            {

                return default(T);
            }
        }

        public T ResolvewithoutManager<T>()
        {
            try
            {
                return Container.Resolve<T>();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }

This obviously works well from my MVC controllers, but what would be a good solution to allow my application to resolve inside my Hub controllers along with my MVC controllers. Currently, I created a singleton class that allows me to resolve my types manually. I can specifically resolve my types inside my Hubs using my the class like this:

InstanceLocator.Instance.Resolve<ISomeInterface>();

While this works, its not ideal from a development standpoint. Reason being, I want my types to be injected and not manually instantiated. My hubs and Controllers are inside the same MVC application and I do not want to have separate them right now.

4

1 回答 1

1

有一整篇文章专门讨论 SignalR 中的依赖注入:http ://www.asp.net/signalr/overview/extensibility/dependency-injection

因此,您所要做的就是为 SignalR 编写一个自定义依赖解析器,这显然将是您常用共享 Unity 容器的简单包装器。

于 2013-10-07T12:56:52.943 回答