gpt4 book ai didi

c# - 在简单注入(inject)器中注册具有构造函数参数的泛型类型

转载 作者:行者123 更新时间:2023-11-30 21:50:48 25 4
gpt4 key购买 nike

如何在简单注入(inject)器中注册具有参数的泛型类型
(最新的 SimpleInjector 版本 v3);

我的界面是;

public interface IDbHelper<T> where T : class
{

void SetInformation(string title, string description);
}

我的类实现;

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) { ... }
}

我试过以下,当然它抛出异常:

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

异常(exception)是;

Error: System.ArgumentException: The constructor of type JsonDbWrapper<T> contains parameter 'path' of type String which can not be used for constructor injection.

我可以创建一个方法来设置路径、文件名和编码。但我希望它们在构造函数中。我想学习使用 Simple Injector 的正确方法。

最佳答案

如果你想为每个助手注册关联的数据库类(例如Person)

选项是向委托(delegate)注册

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

关于c# - 在简单注入(inject)器中注册具有构造函数参数的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com