Unity配置错误 - 类型没有带参数

时间:2016-01-08 09:48:56

标签: c# .net unity-container

背景:我有一个帮助器类,用于设置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来说是个新手

1 个答案:

答案 0 :(得分:1)

构造函数中的参数类型是IExceptionHandler而不是MyExceptionHandler。

尝试:<param name="exceptionHandler" type="IExceptionHandler">