ASP.NET MVC 3 - 更换公共服务定位器时的依赖性解析程序问题

时间:2011-08-31 15:05:47

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

使用Microsoft Unity i注册以下类型:

container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));

在ASP.NET MVC 2中,我可以执行以下操作:

var repository = ServiceLocator.Current
    .GetInstance(typeof(IRepository<>).MakeGenericType(bindingContext.ModelType));

但是在版本3中,我已经删除了所有服务定位器,并实现了新的依赖关系解析器。因此,我将上述内容改为:

var repository = DependencyResolver.Current
    .GetService(typeof(IRepository<>).MakeGenericType(bindingContext.ModelType));

但是现在返回null。

如果它有帮助,这是我对依赖性解析器的实现:

public class UnityDependencyResolver : IDependencyResolver {
    private readonly IUnityContainer _container;

    public UnityDependencyResolver(IUnityContainer container) {
        _container = container;
    }

    public object GetService(Type serviceType) {
        return typeof(IController).IsAssignableFrom(serviceType) ||
            _container.IsRegistered(serviceType) ?
            _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        return _container.ResolveAll(serviceType);
    }
}

如果有人能告诉我自己做错了什么,我真的很感激。感谢

1 个答案:

答案 0 :(得分:1)

我已经没有耐心了,于是决定采用我最初试图避免的Try / Catch方法。这是我的新依赖性解析器:

public class UnityDependencyResolver : IDependencyResolver {
    private readonly IUnityContainer _container;

    public UnityDependencyResolver(IUnityContainer container) {
        _container = container;
    }

    public object GetService(Type serviceType) {
        try {
            return _container.Resolve(serviceType);
        } catch {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        try  {
            return _container.ResolveAll(serviceType);
        } catch {
            return new List<object>();
        }
    }
}

希望这有帮助。