IAppBuilder.CreatePerOwinContext<T> 应该如何使用?

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

我对如何使用 OWIN CreatePerOwinContext 方法感到困惑。据我所知,这是一个穷人的 DI 机制。然而,我没看到如何使用它。

我们可以在启动序列中注册一个 type/implementation,例如:

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

那我们以后怎么解决。文档说它可以通过 Get 方法检索。但是 Get<T> 需要一个字符串参数,它是 Enviornment IDictionary 中该条目的键?在这种情况下我怎么知道密钥?

IUserService userService = context.Get<IUserService>(???);

可以使用typeof获取key参数:

HttpContext.GetOwinContext().Get<ApplicationDbContext>(typeof(ApplicationDbContext).ToString());

此外,Microsoft.AspNet.Identity.Owin 程序集包含 Get<T>() 方法的无参数版本,因此如果您的项目中已有 ASP.NET 身份,则可以使用它。

我自己在 运行 之后有一个更正确的答案,试图在这个 Whosebug 答案中实现代码:

因此在常规配置方法中给出此初始化代码:

static void Configuration(IAppBuilder app)
{
    //
    app.CreatePerOwinContext<AppBuilderProvider>(() => new AppBuilderProvider(app));

    ConfigureAuth(app); //note implementation for this is typically in separate partial class file ~/App_Start/Startup.Auth.cs
}

可以检索此代码创建的实例:

public ActionResult SomeAction() 
{
    //
    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.
}