Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly IAppBuilder.CreatePerOwinContext<T> should be used?

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 register a type/implementation at the Startup sequence like:

app.CreatePerOwinContext<IUserService>(() => {
     return new UserService() as IUserService;
});

Then how do we resolve to that later on. Documentation says it can be retrieved via Get method. But Get<T> expects a string parameter, which is the key to that entry in the Enviornment IDictionary? How can I know the key in this case?

IUserService userService = context.Get<IUserService>(???);
like image 234
BuddhiP Avatar asked Sep 10 '15 11:09

BuddhiP


2 Answers

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.

like image 176
Sergey Kolodiy Avatar answered Oct 13 '22 03:10

Sergey Kolodiy


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.
}
like image 37
enorl76 Avatar answered Oct 13 '22 02:10

enorl76