从2.2升级到3.2后,私有变量为Ninject Interception为

时间:2015-12-08 16:28:03

标签: c# ninject ninject-extensions ninject-interception

我将Ninject从2.2升级到3.2。之前,拦截工作正常,但现在如果我设置断点,我可以看到无参数构造函数在具有Ninject注入的参数的构造函数之后被调用。它之前没有被击中。结果是我的私有变量现在为空。

以下是我的代码:

public class ContentHandler : IContentHandler
{
    IClientGateway _clientGateway;

    protected ContentHandler()
    {
        // This is hit after the other constructer when using Ninject 3.2 but not 2.2.
        // I think this is what is causing _clientGateway to be null.
    }

    public ContentHandler(IClientGateway clientGateway)
    {
        // This gets hit first regardless of Ninject version.
        this._clientGateway = clientGateway;
    }

    public IClientContent GetClientContent(int clientID)
    {
        // _clientGateway is null and throws an exception here :(
        IClient client = this._clientGateway.GetClientbyClientID(clientID);
    }

我做错了什么?在我的global.asax中,我有这个:

kernel.Intercept(ctx => ctx.Request.Service == typeof(IClientGateway))
      .With(InterceptorFactory.GetInterceptor());

InterceptorFactory看起来像这样:

public static class InterceptorFactory
{
    private static IKernel _kernel = new StandardKernel(new LoggingInterceptionModule());

    public static ExceptionInterceptor GetInterceptor()
    {
        return GetExceptionInterceptor();
    }

    private static ExceptionInterceptor GetExceptionInterceptor()
    {
        return _kernel.Get<ExceptionInterceptor>();
    }
}

ExceptionInterceptor如下所示:

public class ExceptionInterceptor : IInterceptor
{
    private LoggingConnector _loggingConnector;
    private const string _logFormat = "Exception occured during invoke of {0} in {1} with arguments {2} EXCEPTION: {3}";

    public ExceptionInterceptor(LoggingConnector lc)
    {
        _loggingConnector = lc;
        _loggingConnector.SetLevel(LogLevel.Error);
    }

    public void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (Exception e)
        {
            _loggingConnector.Write(String.Format(_logFormat, invocation.Request.Method, invocation.Request.Target, invocation.Request.Arguments, e.StackTrace));

            throw e;
        }
    }
}

感谢您的帮助。

0 个答案:

没有答案