简单的注入器 - 自定义WebViewPage

时间:2016-08-01 17:21:23

标签: c# asp.net-mvc dependency-injection ioc-container simple-injector

我是一个使用翻译的小应用程序(目前)。 我的翻译服务称为翻译(ITranslator)。

我的问题是我不想在每个控制器(返回视图)中检索此类,所以我可以在我的视图中使用它。

我与ListService存在类似问题(我存储了所有SelectListItem列表)。

CustomWebViewPage

public abstract class CustomViewPage<TModel> : WebViewPage<TModel>
{
    readonly IScriptFactory scriptFactory;
    readonly IMembership membership;
    readonly IListService listService;
    readonly ITranslator translator;

    IHtmlString path;

    public IMembership Membership { get { return this.membership; } }
    public override IPrincipal User { get { return this.membership.User; } }
    public IListService Lists { get { return this.listService; } }
    public ITranslator Translator { get { return this.translator; } }

    public CustomViewPage(IScriptFactory scriptFactory, IMembership membership,
        IListService listService, ITranslator translator)
    {
        this.scriptFactory = scriptFactory;
        this.membership = membership;
        this.listService = listService;
        this.translator = translator;
    }

    public IHtmlString OwnScriptsPath
    {
        get { return path ?? (path = scriptFactory.Create(this.Html).ToHtmlString()); }
    }

    private string languageHtml =
        "<meta name=\"language\" content=\"" + membership.CurrentLanguage + "\">";
    public IHtmlString MetaLanguage { get { return MvcHtmlString.Create(languageHtml); } }
}

和用法:

<div>
   @Lists.GetNationalities(Model.NationalityId)
</div>

但是,在运行应用程序时,我出现以下错误:

  

&#39; [NAMESPACE] .CustomViewPage&#39;不包含构造函数   需要0个参数

但是如果我创建第二个构造函数,Simple-Injector将抛出一个错误,因为它不支持多个构造函数。

我如何实现我想要的,或者不可能实现?

修改

完整堆栈跟踪

  

c:\ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ Temporary ASP.NET   文件\ VS \ 520dfaa2 \ f5e4578c \ App_Web_index.cshtml.a8d08dba.jtlk7fxz.0.cs(40):   错误CS1729:&#39; SportsHub.SDK.Infrastructure.CustomViewPage&#39;   不包含带0参数的构造函数

at System.Web.Compilation.AssemblyBuilder.Compile()
at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)    at System.Web.Compilation.BuildManager.GetCompiledType(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetCompiledType(String virtualPath)
at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.GetCompiledType(String virtualPath)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)

修改2

正如@StriplingWarrior和@Steven建议的那样,我使用了属性注入,但它似乎并没有在WebViewPage

上工作

我在服务上测试了它,Property Injection成功了,但是在这个类中,属性来了null

PS:我用get; set;

公开了这些属性

新ViewPage:

public abstract class CustomViewPage<TModel> : WebViewPage<TModel>
{
    [Inject]
    public IScriptFactory scriptFactory { get; set; }
    [Inject]
    public IMembership membership { get; set; }
    [Inject]
    public IListService listService { get; set; }
    [Inject]
    public ITranslator translator { get; set; }

    IHtmlString scriptsPath;
    public IHtmlString OwnScriptsPath()
    {
        if (scriptsPath == null)
        {
            scriptsPath = scriptFactory.Create(this.Html).ToHtmlString();
        }
        return scriptsPath;
    }

    /// <summary>
    /// Renders the current user language with a meta tag
    /// </summary>
    public IHtmlString MetaLanguage()
    {
        return MvcHtmlString.Create("<meta name=\"language\" content=\"" + membership.CurrentLanguage + "\">");
    }

对于InjectAttribute,我跟随以下documents

1 个答案:

答案 0 :(得分:0)

您必须使用this之类的寄存器相关性容器。这样,当ASP.NET调用SimpleInject来解析依赖关系时,您可以指定所有接口以及匹配的实现。

您还可以创建一个无参数构造函数:

public CustomViewPage() : base(new ScriptFactory(), new Membership()...) { }

但我不建议......让这种依赖性解析逻辑正常工作是最好的事情。