Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.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
.net DI-类型为的动态参数,其中类型为父对象类型_.net_Configuration_Dependency Injection_Inversion Of Control_Castle Windsor - Fatal编程技术网

.net DI-类型为的动态参数,其中类型为父对象类型

.net DI-类型为的动态参数,其中类型为父对象类型,.net,configuration,dependency-injection,inversion-of-control,castle-windsor,.net,Configuration,Dependency Injection,Inversion Of Control,Castle Windsor,我需要将一个依赖项注入到我的一个类中。这种依赖关系将是暂时的。它又具有类型类型的依赖关系。此类型应为原始类的类型。我只是想知道是否有人知道我该如何进行注册 见示例: public interface ICustomer { ..... } public class Customer : ICustomer { public Customer(IRegister register) { .... } } public interface IRegister {

我需要将一个依赖项注入到我的一个类中。这种依赖关系将是暂时的。它又具有类型
类型
的依赖关系。此类型应为原始类的类型。我只是想知道是否有人知道我该如何进行注册

见示例:

public interface ICustomer
{
    .....
}

public class Customer : ICustomer
{
    public Customer(IRegister register)
    { .... }
}

public interface IRegister
{
    .....
}

public class Register
{
    public Register(Type partentType)
    { .... }
}

public class TestExample
{
    public static void TestMe()
    {
        //If i was creating all this manually it would look
        //   something like this
        IRegister myRegister = new Register(typeof(Customer));
        ICustomer myCustomer = new Customer(myRegister);
    }
}

现在我知道我可以调用
Container.Resolve
当我需要
客户时,然后手动注入
注册
。但是我需要将
Register
注入到我的大多数类中,所以这实际上并不可行。因此,我需要一种通过配置或通过
容器来实现的方法。Register

我不完全确定您是否正在尝试实现这一点,但您可能希望重写您的代码,以便执行以下操作:

public interface IRegister{
    RegisterResult MyMethod(object thing);
}

因此,将实例传递到寄存器中,这样就不需要将类型传递到构造函数中,并且仍然可以使用DI容器。我希望这是有意义的…

我想到了这一点,但这意味着父对象需要了解这个小小的实现怪癖。因此,我将创建一个我无法再执行的依赖项。你认为这是个问题吗

就我试图实现的目标而言,寄存器需要具有父类的类型,才能完成其工作。因此,它是一个强制依赖项。如果不是强制性的,我只需要设置一个属性。我知道我可以使用反射,但出于性能原因,我正试图避免使用反射

另一种选择是,当在customer构造函数的顶部时,我在Registry类上设置类型(通过公共属性)。但是,使用Register的人需要知道这个实现的怪癖,而不是我可以强制执行的怪癖

干杯
Anthony

登记册到底是做什么的?客户对象是否在内部使用过寄存器


我不知道您使用的是哪个DI容器,但假设您使用的是Windsor,您可以使用自定义工具来拦截任何组件创建,然后在那里与您的注册进行交互。这样,您甚至不必让customer类将寄存器作为参数。

我看到的最简单的解决方案是将其更改为

public interface IRegister<TParent> { ... }
public class Register<TParent> : IRegister<TParent>
{
    public Register() { ... }
}

public class Customer : ICustomer
{
    public Customer(IRegister<Customer> register) { .... }
}
公共接口IRegister{…}
公共类注册:IRegister
{
公共寄存器(){…}
}
公共类客户:ICustomer
{
公共客户(IRegister register){….}
}

并将IRegister注册为一个开放的泛型类。

泛型注册如何?ICustomer在我脑海中敲响了警钟。除非您能向我展示至少两个ICCustomer的其他实际实现,否则mock不算,您的设计中有一个缺陷。