Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a class (not an interface) in C#?

I am using Unity here. But probably we just need to be pointed to a right direction.

We know how to inject an interface:

public class AccountController:ApiController
{
    private readonly IAccountRepository _repository;

    public AccountController(IAccountRepository repository)
    {
        _repository = repository;
    }
}

with RegisterType

var container = new UnityContainer();
container.RegisterType<IAccountRepository, AccountRepository>(new HierarchicalLifetimeManager());

But in my AccountRepository, we have a class injected into the constructor.

private readonly ApplicationUserManager _userManager;
public AccountRepository(ApplicationUserManager userManager)
{
    _userManager = userManager;
}

Therefore, when calling the ApiController, I still get this error:

An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.

Stacktrace:

at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

Since I have created some other ApiControllers which worked fine, I guess it must be because our ApplicationUserManager failed to be resolved.

Here ApplicationUserManager is inherited from UserManager instead of an interface. I cannot use container.RegisterType<interface, derived_class>. What is the correct way to resolve it?


Here is the ApplicationUserManager:

public class ApplicationUserManager : UserManager<User>
{
    public ApplicationUserManager(IdentityContext identityContext)
        : base(new UserStore<User>(identityContext))
    {
    }
}

As suggested by some comments below. Here is the RegisterType statements:

var container = new UnityContainer();
container.RegisterType<IAccountRepository, AccountRepository>(new HierarchicalLifetimeManager());
container.RegisterType<ApplicationUserManager, ApplicationUserManager>(new HierarchicalLifetimeManager());
container.RegisterType<IdentityContext, IdentityContext>(new HierarchicalLifetimeManager());

config.DependencyResolver = new UnityResolver(container);

Looks like it takes some special work to set up ASP.NET Identity. I find a link here: Configure Unity DI for ASP.NET Identity. But so far I still could not make it work.

like image 344
Blaise Avatar asked Aug 28 '14 18:08

Blaise


People also ask

Do you need an interface for dependency injection?

There are basically three types of dependency injection: interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

Can we use abstract class instead of interface in dependency injection?

As always, the answer is: "It depends." You can't do these approaches with interfaces as interfaces only specify the contract and don't have implementation. If the contract is all you need, then go with an interface. If you need code to be shared by the subclasses, then go with an abstract class. Save this answer.

How do you inject a class in C#?

Constructor Injection Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.

What is interface injection?

In my understanding, interface injection describes the ability of a bean contener to inject a new interface to the bean, no matter that the class definition of this bean is not implementing it. All examples presented here show how to create a bean out of concrete class, and then how to inject it into another bean.


1 Answers

The problem is that your AccountController class doesn't have a parameterless constructor, the DefaultHttpControllerActivator you see in the stack trace has no idea how to instantiate it.

Fortunately the ASP.NET WebAPI has a built-in way of delegating the controller instantiation task to a DI container. This article covers your use case exactly, and even has source code to download: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

To prevent link rot I've archived the article below (converted the formatting from html as best I could, feel free to improve it):

Dependency Injection in ASP.NET Web API 2

by Mike Wasson

In this article

  1. Software versions used in the tutorial
  2. What is Dependency Injection?
  3. The Web API Dependency Resolver
  4. Dependency Resolution with the Unity Container
  5. Configuring the Dependency Resolver
  6. Dependency Scope and Controller Lifetime

Download Completed Project

This tutorial shows how to inject dependencies into your ASP.NET Web API controller.

Software versions used in the tutorial

  • Web API 2
  • Unity Application Block
  • Entity Framework 6 (version 5 also works)

What is Dependency Injection?

A dependency is any object that another object requires. For example, it's common to define a repository that handles data access. Let's illustrate with an example. First, we'll define a domain model:

C#

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Here is a simple repository class that stores items in a database, using Entity Framework.

C#

public class ProductsContext : DbContext
{
    public ProductsContext()
        : base("name=ProductsContext")
    {
    }
    public DbSet<Product> Products { get; set; }
}

public class ProductRepository : IDisposable
{
    private ProductsContext db = new ProductsContext();

    public IEnumerable<Product> GetAll()
    {
        return db.Products;
    }
    public Product GetByID(int id)
    {
        return db.Products.FirstOrDefault(p => p.Id == id);
    }
    public void Add(Product product)
    {
        db.Products.Add(product);
        db.SaveChanges();
    }

    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

Now let's define a Web API controller that supports GET requests for Product entities. (I'm leaving out POST and other methods for simplicity.) Here is a first attempt:

C#

public class ProductsController : ApiController
{
    // This line of code is a problem!
    ProductRepository _repository = new ProductRepository();

    public IEnumerable<Product> Get()
    {
        return _repository.GetAll();
    }

    public IHttpActionResult Get(int id)
    {
        var product = _repository.GetByID(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

Notice that the controller class depends on ProductRepository, and we are letting the controller create the ProductRepository instance. However, it's a bad idea to hard code the dependency in this way, for several reasons.

  • If you want to replace ProductRepository with a different implementation, you also need to modify the controller class.
  • If the ProductRepository has dependencies, you must configure these inside the controller. For a large project with multiple controllers, your configuration code becomes scattered across your project.
  • It is hard to unit test, because the controller is hard-coded to query the database. For a unit test, you should use a mock or stub repository, which is not possible with the currect design.

We can address these problems by injecting the repository into the controller. First, refactor the ProductRepository class into an interface:

C#

public interface IProductRepository
{
    IEnumerable<Product> GetAll();
    Product GetById(int id);
    void Add(Product product);
}

public class ProductRepository : IProductRepository
{
    // Implementation not shown.
}

Then provide the IProductRepository as a constructor parameter:

C#

public class ProductsController : ApiController
{
    private IProductRepository _repository;

    public ProductsController(IProductRepository repository)  
    {
        _repository = repository;
    }

    // Other controller methods not shown.
}

This example uses constructor injection. You can also use setter injection, where you set the dependency through a setter method or property.

But now there is a problem, because your application doesn't create the controller directly. Web API creates the controller when it routes the request, and Web API doesn't know anything about IProductRepository. This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies. Here is the definition of the interface:

C#

public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

The IDependencyScope interface has two methods:

  • GetService creates one instance of a type.
  • GetServices creates a collection of objects of a specified type.

The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method. I'll talk about scopes later in this tutorial.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

Although you could write a complete IDependencyResolver implementation from scratch, the interface is really designed to act as bridge between Web API and existing IoC containers.

An IoC container is a software component that is responsible for managing dependencies. You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope.

Note

"IoC" stands for "inversion of control", which is a general pattern where a framework calls into application code. An IoC container constructs your objects for you, which "inverts" the usual flow of control.

For this tutorial, we'll use Unity from Microsoft Patterns & Practices. (Other popular libraries include Castle Windsor, Spring.Net, Autofac, Ninject, and StructureMap.) You can use NuGet Package Manager to install Unity. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

console

Install-Package Unity

Here is an implementation of IDependencyResolver that wraps a Unity container.

C#

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        container.Dispose();
    }
}
Note

If the GetService method cannot resolve a type, it should return null. If the GetServices method cannot resolve a type, it should return an empty collection object. Don't throw exceptions for unknown types.

Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

The following code registers the IProductRepository interface with Unity and then creates a UnityResolver.

C#

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}

Dependency Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller's dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:

C#

public IDependencyScope BeginScope()
{
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
}
like image 113
Gabriel Morin Avatar answered Sep 21 '22 13:09

Gabriel Morin