Dependency Injection C# and ASP.NET with Unity

suggest change

Dependency injection decouples a class from the concrete types it uses. This AnimalController creates its dependency itself:

public class AnimalController
{
    private SantaAndHisReindeer _santaAndHisReindeer = new SantaAndHisReindeer();

    public AnimalController()
    {
        Console.WriteLine("");
    }
}

AnimalController now depends on the concrete SantaAndHisReindeer type, which makes the controller harder to reuse and to test.

Why interfaces are used with dependency injection is explained here.

Unity can supply those dependencies. Install the Unity.Mvc package with NuGet.

in Visual Studio Tools -> NuGet Package Manager -> Manage Packages for Solution -> in search input write unity -> choose our project-> click install

The package adds UnityConfig.cs and UnityMvcActivator.cs under App_Start.

RegisterTypes is where a constructor dependency is mapped to a concrete type.

namespace Vegan.WebUi.App_Start
{

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)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your types here
        // container.RegisterType<IProductRepository, ProductRepository>();

        container.RegisterType<ISanta, SantaAndHisReindeer>();
        
     }
 }
}

UnityMvcActivator - > also with nice comments which say that this class integrates Unity with ASP.NET MVC

using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Vegan.WebUi.App_Start.UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(Vegan.WebUi.App_Start.UnityWebActivator), "Shutdown")]
    
namespace Vegan.WebUi.App_Start
{
/// <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();
    }
}
}

The controller can then take the interface that was registered:

public class AnimalController
{
    private readonly ISanta _santaAndHisReindeer;

    public AnimalController(ISanta santaAndHisReindeer)
    {
        _santaAndHisReindeer = santaAndHisReindeer;
    }
}

UnityWebActivator is already marked with PreApplicationStartMethod, so Start runs before Application_Start. Calling it again from Global.asax is unnecessary.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents