I\'m confused on how the OWIN CreatePerOwinContext method is to be used. As far as I can see it\'s a poor mans DI mechanism. Yet, I fail to see how to use it.
We can
I have a more correct answer after running into this myself, trying to implement the code within this stackoverflow answer: https://stackoverflow.com/a/31918218
So given this initialization code within the conventional Configure method:
static void Configuration(IAppBuilder app)
{
//https://stackoverflow.com/a/31918218
app.CreatePerOwinContext<AppBuilderProvider>(() => new AppBuilderProvider(app));
ConfigureAuth(app); //note implementation for this is typically in separate partial class file ~/App_Start/Startup.Auth.cs
}
One can retrieve the instance created by this code:
public ActionResult SomeAction()
{
//https://stackoverflow.com/a/31918218
var app = HttpContext.GetOwinContext().Get<AppBuilderProvider>("AspNet.Identity.Owin:" + typeof(AppBuilderProvider).AssemblyQualifiedName).Get();
var protector = Microsoft.Owin.Security.DataProtection.AppBuilderExtensions.CreateDataProtector(app, typeof(Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
var tdf = new Microsoft.Owin.Security.DataHandler.TicketDataFormat(protector);
var ticket = new AuthenticationTicket(ci, null);
var accessToken = tdf.Protect(ticket);
//you now have an access token that can be used.
}
You can use typeof
to get the key
parameter:
HttpContext.GetOwinContext().Get<ApplicationDbContext>(typeof(ApplicationDbContext).ToString());
Also, Microsoft.AspNet.Identity.Owin
assembly contains the parameterless version of Get<T>()
method, so you can use it if you already have ASP.NET Identity in your project.