0

所以我在放屁,放屁来自《ASP.NET MVC 2 In Action》一书中的演示。没有任何真正的原因只是玩它。我试图用一个真正的 IOC 容器来实现一个示例(他们在示例代码中使用的那个是假的,当然可以工作)。我遇到的问题是 MakeGenericType 返回一个奇怪的类型,名称中有一个反勾号 1。我看了这个问题What does a backtick in a type name mean in the Visual Studio debugger? 这似乎表明它只是为了展示目的?但似乎并非如此。

这是我的代码:

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

这是我试图实现的模型绑定器的代码:

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

调用container.resolve总是会出现以下错误:

依赖解析失败,type = "MvcModelBinderDemo.IRepository`1[MvcModelBinderDemo.Entity]", name = "MvcModelBinderDemo.IRepository`1[[MvcModelBinderDemo.Entity, MvcModelBinderDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ]]”。异常发生时:解决时。

另外,我确实知道将 ref 放入其中MvcApplication有点ModelBinder草率,只是想弄清楚事情是如何工作的以及需要到达容器。

感谢您的任何意见。

4

1 回答 1

1

我认为问题在于您在Resolve. 尝试删除第二个参数repoType.FullName

尝试使用MvcApplication.Container.Resolve(repoType);. 不要忘记using Microsoft.Practices.Unity;在 *.cs 文件的顶部添加。

您链接的问题中已经回答了反引号的含义。但是,你的结论是不正确的。它不仅用于显示目的。带有反引号的名称是您的类的 CLR 名称。
那不是你问题的根源。

于 2012-09-06T04:59:12.113 回答