Unity DI with MVC 5 in controllers

I'm having problems trying to inject dependencies inside the MVC.

The current exception is as follows:

The current type myproject.Core.ToolbarLogic is an interface and cannot be built. Do you miss type mapping?

Debugging I realized that this exception is related to this sentence (included in the Razor view):

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

In the UnityConfig file, all types are registered conveniently, I have an empty constructor in the controller, an exception arises from a place where I cannot access debugging ... Also I read a lot of answers here in StackOverflow and Google, I don’t know what try it now (I tried almost everything).

Does anyone know what the problem is with DI?

The code:

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>

Change 1:

LoadConfiguration, @Nkosi, , - 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)
+6
4

:

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

, .

container.LoadConfiguration(); .

public static void RegisterTypes(IUnityContainer container) {
    // Register the default type in code
    container.RegisterType<IToolbarLogic, ToolbarLogic>();

    // Override with the config file, if there is a unity section.
    if (ConfigurationManager.GetSection("unity") != null) {
        // There is an Unity.config file
        container.LoadConfiguration();
    }        
}

, , .

, , ,

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <!-- other config removed for brevity -->
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="..." />
    <container>
      <register type="IToolbarLogic" />
      <!-- Note the missing mapTo="ToolbarLogic" attribute -->
    </container>
  </unity>
  <!-- other config removed for brevity -->
</configuration>

IToolbarLogic. LoadConfiguration , OP.

.config , . , ToolbarLogic - , . ToolbarLogic IToolbarLogic

public class ToolbarLogic : IToolbarLogic {
    //...other code removed for brevity
}

:

0

mapto,

<container>
  <register type="MyService"> ... </register> <!-- Default registration for type MyService -->
  <register type="ILogger" mapTo="EventLogLogger" /> <!-- type mapping -->
  <register type="ILogger" mapTo="PageAdminLogger" name="emergency" /> <!-- named registration -->
</container>

For more information, use this link .

0
source

you can try this

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

public class ToolbarController : BaseController
{    
    private readonly IToolbarLogic _toolbarLogic;

    public ToolbarController(ToolbarControllerContext context)
    {
        _toolbarLogic = context.ToolbarLogic;
    }


    // 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();
    }
}
0
source

Source: https://habr.com/ru/post/1015906/


All Articles