防止简单的进样器与Umbraco控制器发生冲突

时间:2017-12-14 13:21:44

标签: c# umbraco simple-injector

尽管在我的Umbraco解决方案中只重新使用了我自己的mvc控制器,但简单的注入器似乎也影响了Umbraco的后台控制器。如果我运行下面的代码段,Umbraco后台控制器会遇到异常,类似于this thread中的问题。

我是否还需要添加类似自定义控制器激活器的东西?

protected void Application_Start(object sender, EventArgs e) {

    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    var registeredControllerTypes = 
    SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
        container, Assembly.GetExecutingAssembly())
    .Where(type => type.IsSubClassOf(typeof(MyController)));

    foreach (var controllerType in registeredControllerTypes)
    {
        container.Register(controllerType, controllerType, Lifestyle.Transient);
    }

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

1 个答案:

答案 0 :(得分:3)

解决了@ Steven评论的更新版本:

public class UmbracoConstructorBehavior : IConstructorResolutionBehavior
{
    public IConstructorResolutionBehavior DefaultBehavior { get; set; }
    public ConstructorInfo GetConstructor(Type implementationType)
    {
        return implementationType.Namespace != null 
          && implementationType.Namespace.Contains("Umbraco")
            ? GetUmbracoConstructor(implementationType)
            : DefaultBehavior.GetConstructor(implementationType);
    }

    private ConstructorInfo GetUmbracoConstructor(Type i) => 
       i.GetConstructors().OrderBy(c => c.GetParameters().Length).FirstOrDefault() 
       ?? DefaultBehavior.GetConstructor(i);
}