그래서 "ASP.NET MVC 2 In Action book"의 데모를 보려고합니다. 단지 그걸 가지고 노는 진짜 이유가 아닙니다. 실제 IOC 컨테이너 (예제 코드에서 사용하는 컨테이너는 가짜이며 물론 작동 할 것입니다)로 예제를 구현하려고했습니다. 내가 겪고있는 문제는 MakeGenericType이 이름에 백 틱 1이있는 이상한 유형을 반환한다는 것입니다. 나는이 질문을 What does a backtick in a type name mean in the Visual Studio debugger?에서 보았다. 그리고 그것은 그것이 단지 전시 목적을위한 것이라고 생각하는 것처럼 보일 것인가? 그러나 그렇게 보이지는 않습니다. 여기 내 코드가있다.왜 MakeGenericType이 생성 한 유형에 백틱을 넣을까요?
//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>));
}
다음은 구현하려는 모델 바인더의 코드입니다. 항상 container.resolve하는
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);
}
}
호출이 오류와 불면 : 종속성의
해상도, 이름 = "MvcModelBinderDemo, 실패 유형 ="` 1 MvcModelBinderDemo.Entity]을 MvcModelBinderDemo.IRepository ". IRepository ` 1 [[MvcModelBinderDemo.Entity, MvcModelBinderDemo, 버전 = 1.0.0.0, Culture = 중립, PublicKeyToken = null]] ". 예외가 발생하는 동안 : 해결하는 동안.
도 - ModelBinder에서 MvcApplication을 참조하는 것이 조금 어색하고 컨테이너가 어떻게 작동하는지 알아 내려고하는 것입니다.
입력 해 주셔서 감사합니다.
그럼 유니티에 문제가있을 것입니다. 나는 메서드에 대한 액세스 권한이없는 것 같아요? 한 가지 주장 만하는 결심이 있습니까? 유형? Unity에 ref를 추가하기 위해 NuGet을 사용했습니다. 뭔가를 놓쳤습니까? – Kenn
@Kenn : Resolve [형식 매개 변수 만 사용] (http://msdn.microsoft.com/en-us/library/ff662038(v=pandp.20) .aspx) 및 [ 제네릭 매개 변수] (http://msdn.microsoft.com/en-us/library/ff661102 (v = pandp.20) .aspx). 아마 당신은'using Microsoft.Practices.Unity; '를 추가하는 것을 잊었을 것입니다. –
OK - 마침내 이것으로 돌아 왔고 이제는 repoType = typeof (IRepository <>)라고 말할 수 있습니다. MakeGenericType (bindingContext.ModelType); var repo = (IRepository) MvcApplication.Container.Resolve (repoType); 그러나 그것은 나에게 좋지 않습니다, 나는 여전히 "IReposity'1이 인터페이스이고 건설 될 수 없습니다."- 음? – Kenn