【发布时间】:2016-01-08 20:10:02
【问题描述】:
背景:我有一个帮助类,用于设置ExceptionManager 的策略。在这个类中,我想注入IExceptionHandler 接口的各种实现,我想通过配置文件来控制它。
所以事情是这样的: 助手类和接口:
public class ErrorHelper: IErrorHelper
{
private static IExceptionHandler _exceptionHandler;
public ErrorHelper(IExceptionHandler exceptionHandler)
{
_exceptionHandler = exceptionHandler;
}
public IList<ExeptionPolicyDefinition> GetPolicies()
{
//Do stuff here and return policies
//This is the place where _exceptionHandler is used
}
}
public interface IErrorHelper
{
IList<ExeptionPolicyDefinition> GetPolicies();
}
IExceptionHandler 实现:
public class MyExceptionHandler: IExceptionHandler
{
public MyExceptionHandler()
{
//Do some stuff here
}
public Exception HandleException(Exception exp, Guid iId)
{
//Handle exception and log
}
}
统一引导类:
public class UnityBootstrap
{
private static IUnityContainer _unityContainer;
public static void RegisterTypes(IUnityContainer container)
{
_unityContainer = container;
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(_unityContainer);
}
public static void SetPolicies()
{
var helper = _unityContainer.Resolve<IErrorHelper>();
//Set ExceptionManager and ExceptionPolicy
}
}
Unity 配置文件
<?xml version="1.0" encoding="utf-8"?>
<unity xmlns="http://schemas/microsoft.com/practices/2010/unity">
<alias alias="IExceptionHandler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.IExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<alias alias="MyExceptionHandler" type="TEST.Shared.MyExceptionHandler, Test.Shared"/>
<alias alias="ErrorHelper" type="TEST.Helpers.Errorhelper, TEST.Helpers"/>
<alias alias="IErrorHelper" type="TEST.Helpers.IErrorhelper, TEST.Helpers"/>
<container>
<register type="IExceptionHandler" mapTo="MyExceptionHandler"/>
<register type="IErrorHelper" mapTo="ErrorHelper">
<constructor>
<param name="exceptionHandler" type="MyExceptionHandler">
<dependency type="MyExceptionHandler"/>
</param>
</constructor>
</register>
</container>
</unity>
所以,经过大量的写作和格式化,这是对我所拥有的内容的简化。问题是,当我调用RegisterTypes 时,标题中出现错误,指出没有ErrorHelper 的构造函数接受名称为exceptionHandler 的参数,而构造函数中的参数名称显然是exceptionHandler。
如果有人能指出我在这方面出了什么问题,请这样做。
PS1:抱歉问了这么长的问题
PS2:我对 DI 和 Unity 还很陌生
【问题讨论】:
标签: c# .net unity-container