Afshar
Afshar

Reputation: 11503

What is OWIN equivalent for Application_EndRequest?

I am migrating an ASP.NET Web API application to OWIN. That is not intended to use none OWIN deployments. So Global.asax is going to be removed. There are some code put into Global.asax event handlers specially in Application_EndRequest that should be handled by OWIN.

I have read some article about OWIN and searched the internet but couldn't determine how it can be done. Can anyone please describe how it can be done?

My environment:

UPDATE: Here it is some sections of current code

using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ProjectX.Web.AppStart;
using ProjectY.Domain.Contracts;

namespace ProjectX.UI
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;

            unitOfWork.SaveChanges();
        }
    }
}


namespace ProjectY.Domain.Contracts
{
    public interface IUnitOfWork
    {
        void SaveChanges();
        IRepository<T> GetRepository<T>() where T : class, IEntity, IHistory;
        IDbContext GetDbContext();
    }
}




using ProjectY.Core.Repositories;
using ProjectY.Domain.Contracts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectY.Core.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        public UnitOfWork(IProjectYDbContextFactory contextFactory)
        {
            _context = contextFactory.GetContext();
        }

        public void SaveChanges()
        {
            if (_context == null)
                throw new ApplicationException("Something wrong has been happened. _context must not be null.");

            _context.SaveChanges();
        }
    }
}

Upvotes: 3

Views: 418

Answers (1)

Rob
Rob

Reputation: 2666

I stumbled upon this question while updating some legacy applications. For those still seeking the answer: you can solve this by creating a middleware:

app.Use(async (context, next) =>
{
    await next.Invoke().ConfigureAwait(false);
    //Do stuff after request here!
    var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
    unitOfWork.SaveChanges();
});

You can use stage markers if you need more control on when your middleware will be called in the request processing pipeline.

See also https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline#stage-markers

Upvotes: 1

Related Questions