StructureMap MVC 3 IDependencyResolver

时间:2011-07-21 09:48:46

标签: c# asp.net-mvc-3 structuremap

接口IDependencyResolver有两个方法GetService和GetServices,我实现如下:

public class SmDependencyResolver : IDependencyResolver {

    private readonly IContainer _container;

    public SmDependencyResolver(IContainer container) {
        _container = container;
    }

    public object GetService(Type serviceType) {
        if (serviceType == null) return null;
        try {
              return serviceType.IsAbstract || serviceType.IsInterface
                       ? _container.TryGetInstance(serviceType)
                       : _container.GetInstance(serviceType);
        }
        catch (Exception ex)
        {

            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        return _container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
    }
}

但我还有DependencyResolver的NamedInstace。 这个ObjectFactory.GetNamedInstace(“instanceName”);用于容器 我怎么能这样做..

抱歉我的英文不好

2 个答案:

答案 0 :(得分:1)

您无法使用IDependencyResolver接口检索命名实例。直接访问IContainer。

答案 1 :(得分:1)

创建一个像我在下面所做的扩展方法。 SmDependencyResolver需要将_container变量公开为read属性。

public static class DependencyResolverExtensions
{
        public static object GetService(this IDependencyResolver resolver, Type serviceType, string instanceName)
        {
            var smResolver = resolver as SmDependencyResolver;

            if (smResolver == null) throw new NotSupportedException();

            return smResolver.Container.GetInstance(serviceType, instanceName);
        }
}