StructureMap MVC 3 IDependencyResolver
Interface IDependencyResolver has two method GetService and GetServices that i implement like:
public class SmDependencyResolver : IDependencyResolver {
private readonly IContainer _container;
public SmDependencyResolver(IContainer container) {
_container = container;
}
public object GetService开发者_JS百科(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);
}
}
but i nead also the NamedInstace for DependencyResolver. this ObjectFactory.GetNamedInstace("instanceName"); for container How can i do that..
Sorry for my bad english
Create an extension method like I did below. The SmDependencyResolver would need to expose the _container variable as a read property.
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);
}
}
You cannot retrieve named instances using the IDependencyResolver interface. Access the IContainer directly.
精彩评论