我的计算器配置依赖于'视图(GUI)的定义如下(然后在当前上下文中解析):
Dependencies.register<IView, View>(
"standardView"
);
//Register: calculator release configuration
Dependencies.register<ICalculator, Calculator>(
"releaseCalculator",
(new InjectionProperty(
"IView",
Dependencies.resolve<IView>("standardView")
))
);
//Resolve:
Calculator theCalculator = (Calculator)Dependencies.resolve<ICalculator>(
"releaseCalculator"
);
其中Dependencies是IUnityContainer
的包装器。
Calculator
中的注入点是:
private IView view;
[Dependency]
public IView IView{
get{return view;}
set{view = value;}
}
如果您希望看到Dependencies
的定义,请注意它绝对等同于统一容器的投影,除非我已经延长了对终身经理的直接控制。
问题很简单;给定上述设置,属性IView
在运行时解析为null。就好像Unity只是没有血腥的工作。
@Haukinger这里是包装器:
using System.Collections.Generic;
using Unity;
using Unity.Lifetime;
using Unity.Registration;
namespace Calculator.Utils
{
public static class Dependencies
{
private static IUnityContainer graph;
private static List<KeyValuePair<string, LifetimeManager>> lifetimeManagers;
static Dependencies(){
//container
graph = new UnityContainer();
//instance managers 1 per dependency instance (implementor)
lifetimeManagers = new List<KeyValuePair<string, LifetimeManager>>();
}
//STATES:
public static void register<I, P>(string alias, params InjectionMember[] injections)
{
ContainerControlledTransientManager newLM = new ContainerControlledTransientManager();
lifetimeManagers.Add(new KeyValuePair<string, LifetimeManager>(
alias,
newLM
));
graph.RegisterType(
typeof(I),
typeof(P),
alias,
newLM,
injections
);
}
//function is identitical to Resolve
public static T resolve<T>(string alias)
{
return (T)graph.Resolve(typeof(T), alias);
}
public static void dispose(string alias)
{
LifetimeManager target = (ContainerControlledTransientManager)lifetimeManagers.Find((elem)=>(elem.Key.Equals(alias))).Value;
target.Dispose();
}
}
}
答案 0 :(得分:1)
仅在您请求所有注册类型(即IView[] allViews
)时才会注入命名注册。如果您只请求一个实例,那么您将收到默认注册,在您的情况下只有null
,因为您没有默认注册。
删除名称(standardView
)并将null
作为参数name
传递给RegisterType
,您就可以了。
编辑:此代码在我的机器上正常运行
internal class Program
{
static void Main( string[] args )
{
var container = new UnityContainer();
container.RegisterType<IDependency, MyDependency>((string)null);
var resolved = container.Resolve<Consumer>();
// resolved.Dependency is an instance of MyDependency
}
}
internal class Consumer
{
[Dependency]
public IDependency Dependency { get; set; }
}
public interface IDependency
{
}
internal class MyDependency : IDependency
{
}