Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# SimpleInjector能否在运行时注册泛型类型的初始值设定项?_C#_Dependency Injection_Inversion Of Control_Simple Injector - Fatal编程技术网

C# SimpleInjector能否在运行时注册泛型类型的初始值设定项?

C# SimpleInjector能否在运行时注册泛型类型的初始值设定项?,c#,dependency-injection,inversion-of-control,simple-injector,C#,Dependency Injection,Inversion Of Control,Simple Injector,我可以在运行时向SimpleInjector注册泛型类型的初始值设定项吗?(见下面最后一行代码) 公共类引导程序 { 类型baseTypeGeneric=类型(样本); 公共无效引导(容器) { 变量类型= 从Assembly.getExecutionGassembly().GetTypes()中输入 其中type.Namespace==“NS.xyz” 选择类型; foreach(类型中的类型) { 类型baseType=baseTypeGeneric.MakeGenericType(类型);

我可以在运行时向SimpleInjector注册泛型类型的初始值设定项吗?(见下面最后一行代码)

公共类引导程序
{
类型baseTypeGeneric=类型(样本);
公共无效引导(容器)
{
变量类型=
从Assembly.getExecutionGassembly().GetTypes()中输入
其中type.Namespace==“NS.xyz”
选择类型;
foreach(类型中的类型)
{
类型baseType=baseTypeGeneric.MakeGenericType(类型);
if(type.BaseType==BaseType)
{
容器。寄存器(类型);
}
//我怎样才能让这条线路工作?
container.RegisterInitializer(
x=>container.InjectProperties(x));
}
}
}

解决方案实际上相当简单:在
示例上实现一个非通用接口。这允许您仅为所有示例类型注册一个委托:

公共接口是简单的{}
公共抽象类示例:ISample{}
公共无效引导程序(容器)
{
container.RegisterInitializer(
instance=>container.InjectProperties(实例));
}
由于
RegisterInitializer
将应用于实现
ISample
的所有类型,因此您只需要一次注册

但老实说,在应用属性注入时应该非常小心,因为这会导致很难验证容器配置。将依赖项注入构造函数时,如果缺少依赖项,容器将抛出异常。另一方面,使用属性注入,只需跳过缺少的依赖项,并且不会引发异常。因此,v2.6中的。请回顾一下你的策略。也许你应该重新考虑一下。如果您对您的设计有疑问并且喜欢一些反馈;在Stackoverflow发布一个新问题。

你有点传奇;-)。我在一个非常特定的场景中使用它,将懒散加载处理程序注入到我的数据类中——所有实例中都没有固定的数量。我将再次研究如何使用构造函数,但我确实需要一个默认的空构造函数。
public class BootStrapper
{
    Type baseTypeGeneric = typeof(Sample<>);
    public void BootStrap(Container container)
    {
        var types =
            from type in Assembly.GetExecutingAssembly().GetTypes()
            where type.Namespace == "NS.xyz" 
            select type;

        foreach (Type type in types)
        {
            Type baseType = baseTypeGeneric.MakeGenericType(type);

            if (type.BaseType == baseType)
            {
                container.Register(type);
            }

            //how do I get this line to work?
            container.RegisterInitializer<Sample<[type]>>(
                x => container.InjectProperties(x));
        }
    }
}