I would like to use Ninject capabilities to work with DependencyResolver so I would be able to do something like this:
string contentType = "Page";
IContentRepository<contentTyp开发者_高级运维e> repository = System.Web.Mvc.DependencyResolver.Current.GetService<IContentRepository<contentType>>();
contentType
is dynamic so it can be anything (of a several options) and I don't want to write if..else..
Obviously the above doesn't work. I have to get the Type from the string somehow. IContentRepository is generic and accepts types that derive from ContentBase class, of which Page (in the example above) does.
In MVC 2 with the old Ninject I did it through a custom repository factory (IRepositoryFactory
) which would take the string and then pass that along to the constructor of the repository. But that approach worked with non-generic repositories and it also required special constructors in the repository, which I would like to avoid, if possible.
This is outside of the controller, so I cannot use controller constructor injection (I have that working actually). I'm really stuck with this.
You will have to use reflection to call generics dynamically.
This should work:
var targetType = typeof(IContentRepository<>).MakeGenericType(Type.GetType(contentType));
object repository = System.Web.Mvc.DependencyResolver.Current.GetType().GetMethod("GetService").MakeGenericMethod(targetType).Invoke(System.Web.Mvc.DependencyResolver.Current, null);
精彩评论