简体   繁体   English

在 Simple Injector 中注册具有多个构造函数和字符串依赖项的类型

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

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.我试图弄清楚如何使用 Simple Injector,我已经在项目中使用它,注册简单服务及其组件没有问题。

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.对于能够创建 DAL 的容器,它应该只包含一个公共构造函数,但它有 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. DAL 类型的构造函数包含不能用于构造函数注入的 String 类型的参数“databaseInstance”。

Is there any way where I can do dependency injection where the class has more than 2 public constructors?有什么方法可以在类有 2 个以上公共构造函数的情况下进行依赖注入? Or having one public constructor that accepts a parameter?或者有一个接受参数的公共构造函数?

I read the documentation here: SimpleInjector (Getting Started)我在这里阅读了文档: 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.该文档一开始很容易理解,但它变得非常复杂,我很难破译他们提到的后一个例子是否与我的问题有关。

There are two things about your class that prevents Simple Injector from being able to auto-wire your DAL class:你的类有两件事会阻止 Simple Injector 自动连接你的 DAL 类:

  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. Nemesv 的评论几乎是正确的。 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. 本文介绍了为什么您的应用程序组件应该只有一个构造函数。

If constructor is looking for string value container.Register(() => new DAL("db"));如果构造函数正在寻找字符串值 container.Register(() => new DAL("db"));

If constructor is looking for another class如果构造函数正在寻找另一个类

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM