简体   繁体   English

在Simple Injector中注册具有构造函数参数的泛型类型

[英]Register generic types that have constructor arguments in Simple Injector

How to register generic types that have arguments in Simple Injector 如何在Simple Injector中注册具有参数的泛型类型
(latest SimpleInjector version v3); (最新的SimpleInjector版本v3);

My interface is; 我的界面是;

public interface IDbHelper<T> where T : class
{

    void SetInformation(string title, string description);
}

My class implementation; 我的课堂实施;

public class JsonDbWrapper<T> : IDbHelper<T> where T : class
{
    private readonly JsonDb<T> _jsonFile;

    public JsonDbWrapper(string path, string filename, Encoding encoding)
    {
        _jsonFile = JsonDb<T>.GetInstance(path, filename, encoding);
    }


    public void SetInformation(string title, string description) { ... }
}

I tried following, ofcourse it's throwing an exception: 我尝试了以下操作,当然会引发异常:

container.Register(typeof(IDbHelper<>), typeof(JsonDbWrapper<>));

Exception is; 例外是;

Error: System.ArgumentException: The constructor of type JsonDbWrapper<T> contains parameter 'path' of type String which can not be used for constructor injection. 错误:System.ArgumentException: JsonDbWrapper<T>类型的构造函数包含String类型的参数'path',该参数不能用于构造函数注入。

I can create a method to set path, filename and encoding. 我可以创建一种设置路径,文件名和编码的方法。 But I want them in constructor. 但是我想要它们在构造函数中。 I want to learn proper way of using Simple Injector. 我想学习使用简单注入器的正确方法。

if you want to register each helper with associate db class (eg Person) 如果要向每个帮助程序注册相关的db类(例如Person)

the option is to register with delegate 选项是向代表注册

container.Register<IDbHelper<Person>>(() => new JsonDbWrapper<Person>("path","filename",Encoding.UTF8));
var result = container.GetInstance<IDbHelper<Person>>();

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

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