C# 统一组建的工厂模式<;T>;麻烦
我的演示代码非常简单C# 统一组建的工厂模式<;T>;麻烦,c#,unity-container,inject,C#,Unity Container,Inject,我的演示代码非常简单 using Microsoft.Practices.Unity; using System; public interface IDecorator { string GetA(); } public class Decorations:IDecorator { public string GetA() { return "temp"; } } public class Base { } public class
using Microsoft.Practices.Unity;
using System;
public interface IDecorator
{
string GetA();
}
public class Decorations:IDecorator
{
public string GetA()
{
return "temp";
}
}
public class Base
{
}
public class Derive : Base
{
[Dependency]
public IDecorator DerivedDecorations { get; set; }
}
public class Program
{
private static void Main(string[] args)
{
Base bd = new Derive(); // here is the point
var container = new UnityContainer();
container.RegisterType<IDecorator, Decorations>();
container.BuildUp(bd); // bd.DerivedDecorations is null
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
使用Microsoft.Practices.Unity;
使用制度;
公共接口IDecorator
{
字符串GetA();
}
公共类装饰:IDecorator
{
公共字符串GetA()
{
返回“temp”;
}
}
公共阶级基础
{
}
公共类派生:基
{
[依赖性]
公共IDecorator{get;set;}
}
公共课程
{
私有静态void Main(字符串[]args)
{
Base bd=new derivate();//这里是要点
var container=new UnityContainer();
container.RegisterType();
container.build(bd);//bd.derivedEditions为空
Console.WriteLine(“按任意键继续…”);
Console.ReadKey();
}
}
在上述情况下,无法解析派生类中的DerivedDetrictions
如果我们将代码更改为derivebd=new-deriver()代码>没有问题
我不清楚原因,因为我们使用的是工厂模式,有人能给我一些原因吗?看看通用重载
Unity使用指定类型的T来检查它的属性并确定要注入的依赖项
在您的例子中,您没有显式地指定T,而是依赖于,它解析为类“Base”(因为参数变量类型是“Base”类型)
因此,要么相应地声明变量,要么通过以下途径尝试另一种方法:
或
在给定的示例中,这一点目前没有什么意义,但为了简单起见,我希望对您的示例进行分解。为什么不直接执行derivetemp=new-deriver();容器积层(温度);导出bd=温度代码>因为我们使用工厂。。。。代码类似于Base b=get派生()……另一个提示:可能不“构建”现有实例,而是让工厂通过容器创建实例,在这种情况下,完整类型是已知的。这将推断“派生”也需要在容器中注册。
container.BuildUp(typeof(Derived), bd);
container.BuildUp(bd.GetType(), bd); //which resolves to "Derived"