SaaS CMS has officially launched! Learn more now.

IOwinContext in Scheduled Job

Vote:
 

Hi guys,

I have a job that needs to get a user by username for our front end authentication which is using AspNet Identity. The job itself is running without HttpContext and therefore HttpContext.Current.GetOwinContext() to get the OwinContext are failing. I've seen people showing examples of custom middleware for Web API but that's obviously a sightly different context.

Does anyone have any ideas or working code on getting this working without a HttpContext?

#196274
Aug 23, 2018 17:19
Vote:
 

anyone? 

#196364
Aug 28, 2018 10:28
Vote:
 

I think your best bet is to just use the ApplicationDbContext<SiteUser> directly, like so:

using (var userDbContext = new ApplicationDbContext<SiteUser>(connectionString))
{
    var user = userDbContext.Users.FirstOrDefault(x => x.Email == email);
}

And if you want to use exactly that instance in any other dependency during your job, you could create a nested container for your job, like so:

using (var container = _container.GetNestedContainer())
{
    using (var userDbContext = new ApplicationDbContext<SiteUser>(connectionString))
    {
        container.Inject(userDbContext);
        var dependency = container.GetInstance<IDependency>();
        dependency.DoStuff();
    }
}

The inject method replaces any existing instance of the provided type, and more importantly - it tells StructureMap not to use your regular ApplicationDbContext<SiteUser> which was probably registered using () => HttpContext.Current.GetOwinContext().Get<ApplicationUserManager<SiteUser>>.

The nested container disposes all its created objects at the end of the using statement, so using a nested container is probably a good idea in any case. It defines a obvious lifecycle for your dependencies.

This also means, of course, that you move your dependencies from the constructor (which only needs a IContainer) to resolving them via the nested container.

#203527
Apr 26, 2019 10:56
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.