Search code examples
c#asp.net-web-apirepositoryasp.net-identityautofac

OWIN Self-Host Web API 2: How to Inject current user into generic Repository using Autofac


I'm building a OWIN Self-Hosted Web API 2 application and I'm using a generic repository pattern and using Autofac for dependency injection.

My generic repository class;

public abstract class Repository<T> : IRepository<T> where T : BaseEntity
{
  private DbContext context_;
  private Identity _currentUser; //This needs to be resolved

  public Repository(DbContext context)
  {
      context_ = context;
  }

  public T Update(T item)
  {
      //item.ModifiedBy = _currentUser.UserName; // The value needs to be assigned
      context_.SaveChanges();
      return item;
  }

}

Problem:

I need to access the current user and I need to update the database with ModifiedBy field.

I'm trying to avoid constructor injection, as the repository object is created in several places in project by passing DbContext as a constructor argument.

Is there any alternative ways to do this without modifying existing code much. Could anyone help me to achieve my requirement.

Note:

Alternatively I can override the SaveChanges() method in DbContext class. But again I cannot access the current there.


Solution

  • Identity is accessed from Thread.CurrentPrincipal.Identity, there is no problem setting this to whatever in a test setup eg. Thread.CurrentPrincipal = new ClaimsPrincipal(identity);

    Edited

    Yes CurrentPrincipal is safe to use, you would normally create some utilities functions to read out the values you need. Or you could of course create your own abstraction, and inject that to your classes, but I don't see the point of that.

    btw. generic repositories are never a wise choice (read up on DDD).