开发者

ASP.NET MVC 3 - Dependency Resolver Issue When Replacing the Common Service Locator

开发者 https://www.devze.com 2023-03-31 20:24 出处:网络
Using Microsoft Unity i register the开发者_如何学C following type: container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));

Using Microsoft Unity i register the开发者_如何学C following type:

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

In ASP.NET MVC 2 i could then do the following:

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

But in version 3. I have removed all occurances of the Service Locator and implemented the new Dependency Resolver instead. Therefore i changed the above to:

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

However this now returns null.

Here is my implementation of the Dependency Resolver if it helps:

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);
    }
}

I'd really appreciate it if someone could show me what i've done wrong. Thanks


i've run out of patience and decided to go for the Try/Catch approach i was initially trying to avoid. Here is my new Dependency Resolver:

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>();
        }
    }
}

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号