Chris W
Chris W

Reputation: 1802

When using Ninject2 InRequestScope can Dispose be replied upon for cleanup?

In an application I'm working on I've created a lightweight logger which has two purposes. Errors logged with the enum "Domain" will get logged to a database, whilst errors logged with the enum "Application" can be pulled from a service to be displayed to a user.

I'm using ninject InRequestScope to allow for the error collection to be maintained over the scope of the request.

One issue I'm uncertain about is when should I call the function to log errors to the database. This function pushes all errors into the DB using a Transaction. An idea I had was to make the error logger use IDisposable and then call the LogErrorsToDatabase() method from the Dispose method.

Are there any issues with doing this?

Will ninject automatically call dispose, or do I need to configure it to do so?

I first tried to inject the service into Global.asax, but this had unforseen issues.

EDIT: I found a way to do this more elegantly, so for future reference, I'll detail it below.

I first created a custom action filter and used property injection to inject the IErrorLog service:

public class LogErrorsAttribute : ActionFilterAttribute
{
    [Inject]
    public IErrorQueue ErrorQueue { private get; set; }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        ErrorQueue.CommitDatabaseLog();
        base.OnResultExecuted(filterContext);
    }
}

I next used Ninject's BindFilter method to bind this function to every called action:

 BindFilter<LogErrorsAttribute>(FilterScope.Last, 0);

Everything works perfectly and cleanly now.

Final Edit: I noticed someone has upvoted this recently, so they might have used the solution I found. I did discover a bug with the solution in the last edit. It seems that my navigation controller was firing this function, at the point that the navigation fired, no errors had occured, this wrote to the filtercontext and stopped it functioning when called by the action later down the chain. To resolve this, I used the following binding code:

kernel.BindFilter<LogErrorsAttribute>(FilterScope.Last, 0).When(
            (context, ad) => !string.IsNullOrEmpty(ad.ActionName) && ad.ControllerDescriptor.ControllerName.ToLower() != "navigation");

This stops the filter being fired by any navigation code (partial views being rendered from the controller.)

Upvotes: 3

Views: 303

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

Yes Ninject will dispose objects in request scope.

Upvotes: 4

Related Questions