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

断了今生、忘了曾经 提交于 2020-02-01 00:37:36

问题


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.


回答1:


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.




回答2:


If constructor is looking for string value container.Register(() => new DAL("db"));

If constructor is looking for another class

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


来源:https://stackoverflow.com/questions/20892191/registering-a-type-with-multiple-constructors-and-string-dependency-in-simple-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!