So I am farting around with a demo from the book "ASP.NET MVC 2 In Action". Not for any real reason just playing with it. I tried to implement an example with a real IOC container (the one they use in the sample code is fake and will of course work). The problem I am having is that MakeGenericType returns a weird type with a back tick 1 in the name. I looked at this question What does a backtick in a type name mean in the Visual Studio debugger? and that would seem to suggest it is just for display purposes? but it doesn't seem that way.
Here is my code:
//here are the ways I tried to register the types
private static void InitContainer()
{
if (_container == null)
{
_container = new UnityContainer();
}
_container.RegisterType<IMessageService, MessageService>();
_container.RegisterType<IRepository, Repository>();
_container.RegisterType(typeof(IRepository<Entity>), typeof(Repository<Entity>));
}
Here is the code from the model binder I am trying to implement:
public class EntityModelBinder: IFilteredModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null)
return null;
if (string.IsNullOrEmpty(value.AttemptedValue))
return null;
int entityId;
if (!int.TryParse(value.AttemptedValue, out entityId))
return null;
Type repoType = typeof (IRepository<>).MakeGenericType(bindingContext.ModelType);
var repo = (IRepository)MvcApplication.Container.Resolve(repoType, repoType.FullName, new ResolverOverride[0]);
Entity entity = repo.GetById(entityId);
return entity;
}
public bool IsMatch(Type modelType)
{
return typeof (Entity).IsAssignableFrom(modelType);
}
}
The call to container.resolve
always blows up with the following error:
Resolution of the dependency failed, type = "MvcModelBinderDemo.IRepository`1[MvcModelBinderDemo.Entity]", name = "MvcModelBinderDemo.IRepository`1[[MvcModelBinderDemo.Entity, MvcModelBinderDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]". Exception occurred while: while resolving.
Also, I do know that putting the ref to MvcApplication
in the ModelBinder
is a little sloppy, just trying to figure out how things work and needed to get to the container.
Thanks for any input.
I think the problem is that you are explicitly specifying a name in the Resolve
. Try removing the second parameter repoType.FullName
.
Try using MvcApplication.Container.Resolve(repoType);
. Don't forget to add using Microsoft.Practices.Unity;
at the top of your *.cs file.
What the meaning of the backtick is has already been answered in the question you linked. However, your conclusion is not correct. It is not just for display purposes. The name with the backtick is the CLR name of your class.
That is not the source of your problem.