我正在尝试使用Microsoft站点中提供的以下示例。在按类型解析时给出编译时错误。
http://msdn.microsoft.com/en-us/library/vstudio/hh323725(v=vs.100).aspx
是代码中的问题,如何解决?
public class DependencyInjectionInstanceProvider : IInstanceProvider
{
private readonly Type _ServiceType;
public DependencyInjectionInstanceProvider(Type serviceType)
{
_ServiceType = serviceType;
}
public object GetInstance(InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
public object GetInstance(InstanceContext instanceContext, Message message)
{
return DependencyFactory.Resolve(_ServiceType); //error
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
}
}
public class DependencyFactory
{
private static IUnityContainer _container;
public static IUnityContainer Container
{
get
{
return _container;
}
private set
{
_container = value;
}
}
static DependencyFactory()
{
var container = new UnityContainer();
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
if (section != null)
{
section.Configure(container);
}
_container = container;
}
public static T Resolve<T>()
{
T ret = default(T);
if (Container.IsRegistered(typeof(T)))
{
ret = Container.Resolve<T>();
}
return ret;
}
}
答案 0 :(得分:0)
很抱歉很长时间的回答,但我这些天才开始使用Unity。 也许你必须这样打电话:
DependencyFactory.Resolve<_ServiceType>();
我认为问题在于您在调用者中将类型视为参数。 请查看此链接http://msdn.microsoft.com/en-us/library/ff650319.aspx
答案 1 :(得分:0)
示例代码包含DependencyFactory.Resolve<T>()
但不是DependencyFactory.Resolve(Type typeToResolve)
。
您可以实现DependencyFactory.Resolve(Type typeToResolve)复制示例逻辑(请参阅Programmatic equivalent of default(Type)以使用Type创建默认值)。
最简单的解决方案是访问容器成员。
请务必使用Microsoft.Practices.Unity;
public object GetInstance(InstanceContext instanceContext, Message message)
{
return DependencyFactory.Container.Resolve(_serviceType);
}