2
\$\begingroup\$

here I leave my code for a repository pattern with NHibernate and Autofac. I would like to receive some feedback about it. Especially about the session handling with NHibernate. By now I don't like the way that is implemented. Currently the session is created in an IHttpModule on the beginning of the request. Could this session be created with Autofac?.

ISessionModule

public class ISessionModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
        context.RequestCompleted += context_requestCompleted;
    }
    private void context_BeginRequest(object sender, EventArgs e)
    {
        NHibernateHelper.GetCurrentSession();
    }
    private void context_requestCompleted(object sender, EventArgs e)
    {
        NHibernateHelper.CloseSessionFactory();
    }
    public void Dispose()
    {
        //throw new NotImplementedException();
    }
}

Repository class

public class BaseRepository<T,TId> : IRepository<T, TId> where T : class
{
    protected ISession session = HttpContext.Current.Items["nhibernate.current_session"] as ISession;
    protected ITransaction transaction = null;
    public BaseRepository()
    {
        //session = NHibernateHelper.OpenSession();
        transaction = session.BeginTransaction();
    }
    public async void Create(T entity)
    {
        await session.SaveOrUpdateAsync(entity);
        await transaction.CommitAsync();
    }
    public async void DeleteAsync(TId key)
    {
        var entity = await session.LoadAsync<T>(key);
        await session.DeleteAsync(entity);
        await transaction.CommitAsync();
    }

    public async Task<List<T>> FindAll()
    {
         return await session.Query<T>().ToListAsync();
    }

    public async Task<T> FindOne(TId key)
    {
         return await session.GetAsync<T>(key);
    }

    public async void Update(T entity)
    {
        await session.SaveOrUpdateAsync(entity);
        await transaction.CommitAsync();
    }
}

Example of the controller

public class ContractsController : ODataController
{
    private readonly BaseRepository<Contract, int> contractRepository;
    public ContractsController(BaseRepository<Contract, int> contractRepository)
    {
        this.contractRepository = contractRepository;
    }
    public async Task<IHttpActionResult> Get([FromODataUri] int key)
    {
        var contract = await contractRepository.FindOne(key);
        if (contract == null)
        {
            return StatusCode(HttpStatusCode.NotFound);
        }
        return Ok(contract);
    }

Global.asax

    public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var builder = new ContainerBuilder();
        builder.RegisterGeneric(typeof(BaseRepository<,>)).As(typeof(BaseRepository<,>)).InstancePerRequest();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        var container = builder.Build();
        var webApiResolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.