StructureMap MVC 3 IDependencyResolver

本文关键字:IDependencyResolver MVC StructureMap | 更新日期: 2023-09-27 18:02:53

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

但是我也需要nameinstace的DependencyResolver。都这ObjectFactory.GetNamedInstace(");集装箱我怎么能那样做呢?

对不起,我的英语不好

StructureMap MVC 3 IDependencyResolver

创建如下所示的扩展方法。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);
        }
}

不能使用IDependencyResolver接口检索命名实例。直接访问iconcontainer

相关文章:
  • 没有找到相关文章