MEF를 asp.net mvc와 함께 사용하고 싶습니다. 나는 내 컨트롤러 공장을 설정하고있어MEF 및 ASP.NET MVC
Global.asax.cs에서public class MefControllerFactory : DefaultControllerFactory
{
private CompositionContainer _Container;
public MefControllerFactory(Assembly assembly)
{
_Container = new CompositionContainer(new AssemblyCatalog(assembly));
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType != null)
{
var controllers = _Container.GetExports<IController>();
var controllerExport = controllers.Where(x => x.Value.GetType() == controllerType).FirstOrDefault();
if (controllerExport == null)
{
return base.GetControllerInstance(requestContext, controllerType);
}
return controllerExport.Value;
}
else
{
throw new HttpException((Int32)HttpStatusCode.NotFound,
String.Format(
"The controller for path '{0}' could not be found or it does not implement IController.",
requestContext.HttpContext.Request.Path
)
);
}
}
}
: 나는 다음과 같은 컨트롤러 공장을 썼다
[Export(typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller
{
private readonly IArticleService _articleService;
[ImportingConstructor]
public HomeController(IArticleService articleService)
{
_articleService = articleService;
}
//
// GET: /Articles/Home/
public ActionResult Index()
{
Article article = _articleService.GetById(55);
return View(article);
}
}
IArticleService
가 있습니다 :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory.MefControllerFactory(Assembly.GetExecutingAssembly()));
}
나는 지역이 인터페이스.
IArticleService
을 구현하고 내보내는 클래스가 있습니다.
작동합니다.
MEF에서 필요한 모든 것입니까?
컨트롤러에 대해 PartCreationPolicy
및 ImportingConstructor
설정을 건너 뛸 수 있습니까?
생성자를 사용하여 내 의존성을 설정하고 싶습니다. PartCreationPolicy
이없는 때, 나는 예외 다음 얻을
은 :
컨트롤러의 단일 인스턴스 'MvcApplication4.Areas.Articles.Controllers.HomeController는'여러 요청을 처리하는 데 사용할 수 없습니다. 사용자 정의 컨트롤러 팩토리가 사용 중이면 각 요청에 대해 컨트롤러의 새 인스턴스를 생성해야합니다.
asp.net MVC의 MEF는 부분 신뢰 환경에서는 매우 친숙하지 않습니다. 예를 들어, 괴상한 저녁 식사 MEF 샘플은 부분 신뢰 시나리오에서 훌륭하게 폭발 할 것입니다. 기본적으로 부분 신뢰에서는 MEF 내부의 여러 부분이 부분적으로 신뢰할 수있는 코드에서 액세스 할 수 없으므로 MEF 사용 방법이 매우 제한적입니다. –
MEF 대신 Unity를 사용하기로 결정했습니다. –