mvc

Manual Dependency Injection in MVC - Trickcode

how to perform dependency injection manually, ASP.NET MVC,dependency injection
Share it:

how to perform dependency injection manually


Back in part one, I discussed what dependency injection was and why you should use it. In this part, I’m going to cover how to perform dependency injection manually. I’ll use the example of a controller that uses a service class that depends on a repository.


First up is the repository. Here we’ll create an interface IRepo and class DbRepo. IRepo will get used later. DbRepo will have two constructors. One that accepts a connection string and one that’s parameterless which calls the other one passing a default connection string. This allows us to change the database connection for testing.



public interface IRepo
{
    // Required methods
}
 
public class DbRepo : IRepo
{
    public DbRepo(string dsn)
    {
        // Connect here
    }
 
    public DbRepo()
        : self("Default Connection String")
    {
    }
}

Now let’s create an interface for our business logic that we’ll use later and a class that implements it. Similar to the repository it will have a constructor that takes one parameter, this time an instance of IRepo, and one that’s parameterless which calls the other constructor passing an instance of DbRepo.

public IBusinessLogic
{
    // Declare methods here
}
 
public AppBusinessLogic
{
    private IRepo _repo;
 
    public AppBusinessLogic(IRepo repo)
    {
        _repo = repo;
    }
 
    public AppBusinessLogic
        : self(new DbRepo())
    {
    }
}

You probably guessed that we’ll do something similar to the controller.

public class AppController
{
    private IBusinessLogiv _service;
 
    public AppController(IBusinessLogic service)
    {
        _service = service;
    }
 
    public AppController()
        : self(new AppBusinessLogic())
    {
    }
}

When ASP.NET MVC runs it will use the parameterless constructor for the controller which will cause default instances of IBusinessLogic and IRepo to be created and used. This method, while effective, is pretty clumsy. You have no way of controlling what the default instances are on a case by case basis, nor can you control re-use of created instances.
Share it:

mvc

Post A Comment:

0 comments: