AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

Manual Dependency Injection in MVC - Trickcode

By pushpam abhishek
Listen to this article

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 this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments