c# - Controller 中带有 MVC 5 的 Unity DI

标签 c# asp.net-mvc razor asp.net-mvc-5 unity-container

我目前在尝试在 MVC Controller 中进行依赖注入(inject)时遇到问题。

当前异常如下:

The current type, myproject.Core.ToolbarLogic, is an interface and cannot be constructed. Are you missing a type mapping?

调试我意识到这个异常是从这句话引发的(包含在 Razor View 中):

@{ Html.RenderAction("Toolbar", "Toolbar");  }

在UnityConfig文件中,方便的注册了所有类型, 我在 Controller 中有一个空的构造函数, 异常是从我无法访问调试的地方引发的...此外,我在 StackOverflow 和 Google 中阅读了很多答案,我现在不知道该尝试什么(我几乎尝试了所有方法)。

有人知道 DI 有什么问题吗?

代码:

ToolbarController.cs

public class ToolbarController : BaseController
{

    [Dependency]
    public IToolbarLogic ToolbarLogic { get; set; }

    public ToolbarController()
    {
    }


    // GET: Common/Toolbar
    public ActionResult Toolbar()
    {
        bool ShowConfidential = ToolbarLogic.ShowConfidential();
        string linkHome = ToolbarLogic.BindHome(base.User.Identity.Name);
        return PartialView(new ToolbarModel() {
            ShowConfidential = ShowConfidential,
            lnkHome = linkHome
        });
        return PartialView();
    }

}

UnityWebActivator.cs

/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        var container = UnityConfig.GetConfiguredContainer();

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

UnityConfig.cs

    /// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    /// <summary>Registers the type mappings with the Unity container.</summary>
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IToolbarLogic, ToolbarLogic>();

        // There is an Unity.config file
        container.LoadConfiguration();
    }
}

Unity.config

<?xml version="1.0"?>
<!-- Configuración de Unity -->
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>


  </container>
</unity>

编辑 1:

正如@Nkosi 所说,我已经对 LoadConfiguration 行进行了评论,因为这是有道理的,因为我的 Unity.config 中没有任何相关信息(见上文,它是空的)。

错误还是一样:

Resolution of the dependency failed, type = "MVCControls.Controllers.ToolbarController", name = "(none)".
Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, interfaces_logic.Interfaces.IToolbarLogic, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving MVCControls.Controllers.ToolbarController,(none)
  Resolving value for property ToolbarController.ToolbarLogic
  Resolving interfaces_logic.Interfaces.IToolbarLogic,(none)

最佳答案

尝试用以下内容替换 Controller 的构造函数:

public ToolbarController(IToolbarLogic toolbarLogic)
{
    this.ToolbarLogic = toolbarLogic;
}

关于c# - Controller 中带有 MVC 5 的 Unity DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42926667/

相关文章:

html - 使用 CSS :empty pseudoclass 格式化 Razor cshtml 文件

c# - 如何在 Windows 10 应用中实现应用内购买?

c# - 如何在获得焦点后立即将单元格置于编辑模式

c# - MODI.Image 来自(位图)图像未保存在硬盘上。

c# - 代码隐藏中的翻转 View 动画

asp.net-mvc - 在剑道网格列中显示自定义值

javascript - 将 .aspx 页面 html 渲染/调用到另一个 .aspx 页面

c# - 如何防止在 mvc 中多次选择 Razor 控件单选按钮?

asp.net-mvc - {01/01/0001 00 :00:00} being passed as default date and time, MVC 2

razor - 从 ASP.NET Core 1.0 中的 ViewModel 元数据输入占位符