Registering a type with multiple constructors and string dependency in Simple Injector

sksallaj picture sksallaj · Jan 2, 2014 · Viewed 13.3k times · Source

I'm trying to figure out how to use Simple Injector, I've used it around the project with no problems registering simple services and their components.

However, I wanted to use dependency injector when having a component with more than two constructors that implements an interface.

public DAL: IDAL
{
    private Logger logger;
    string _dbInstance;
    public DAL()
    {
        logger = new Logger();
    }

    public DAL(string databaseInstance)
    {
         logger = new Logger();
         _dbInstance = databaseInstance;
    }
}

Here is how I'm registering the services:

container.Register<IDAL, DAL>();

running the code, this is the error that happens:

For the container to be able to create DAL, it should contain exactly one public constructor, but it has 2.

After removing the constructor, the next error is that it doesn't allow my constructor to accept a parameter.

The constructor of type DAL contains parameter 'databaseInstance' of type String which can not be used for constructor injection.

Is there any way where I can do dependency injection where the class has more than 2 public constructors? Or having one public constructor that accepts a parameter?

I read the documentation here: SimpleInjector (Getting Started)

The document starts of easy to understand, but it gets exponentially complex and I'm having a tough time trying to decipher if any of the latter examples they mention relate to my issue.

Answer

Steven picture Steven · Jan 3, 2014

There are two things about your class that prevents Simple Injector from being able to auto-wire your DAL class:

  1. Your class has two constructors and
  2. If you remove the default constructor, primitive types such as strings can't be injected.

Nemesv is almost right in his comment. You can fallback to using a delegate registration like this:

container.Register<IDAL>(() => new DAL("db"));

This article describes why your application components should have only one constructor.