在Simple Injector中注册具有多个构造函数和字符串依赖性的类型 [英] Registering a type with multiple constructors and string dependency in Simple Injector

查看:85
本文介绍了在Simple Injector中注册具有多个构造函数和字符串依赖性的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用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.

但是,当一个组件具有两个以上的实现接口的构造函数时,我想使用依赖项注入器。

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:


要使容器能够创建DAL,它应该恰好包含一个公共构造函数
,但是它具有2个。

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.


DAL类型的构造函数包含
类型字符串的参数'databaseInstance',不能用于构造函数注入。

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?

我在这里阅读了文档: SimpleInjector(入门)

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.

推荐答案

关于您的班级,有两件事使Simple Injector无法自动连接DAL班级:

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


  1. 您的班级有两个构造函数和

  2. 如果删除默认构造函数,则不能注入诸如字符串之类的基本类型。

Nemesv在他的评论中几乎是正确的。您可以退回使用这样的委托注册:

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.

这篇关于在Simple Injector中注册具有多个构造函数和字符串依赖性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆