0

I want to have access into my DbContext from factory service to use it in parameterless [Auth] in Controllers. I use Simple Injector for DI.

Current Attribure class:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class AuthAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    bool Active = true;

    public AuthAttribute()
    {
    }

    public AuthAttribute(bool active)
    {
        Active = active;
    }

    private readonly IMyContextFactory _contextFactory;

    public AuthAttribute(IMyContextFactory contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public void OnAuthorization(AuthorizationFilterContext filterContext)
    {
        if (!Active)
        {
            return;
        }

        // TODO: Use INITIALIZED IMyContextFactory...
        //var dbContext = _contextFactory.GetContext();
        var dbContext = (MyContext) filterContext.HttpContext.RequestServices.GetService(typeof(MyContext));
    }
}

My current registration in SI:

_container.Register<AuthAttribute>(() => new AuthAttribute(_container.GetInstance<IMyContextFactory>()), Lifestyle.Scoped);

Current issue: both dbContext is null - _contextFactory is null, and there is no service in filterContext.HttpContext.RequestServices

Saibamen
  • 610
  • 3
  • 17
  • 43

0 Answers0