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

Bud*_*hiP 7 c# dependency-injection owin

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

我们可以在Startup序列中注册一个类型/实现,如:

app.CreatePerOwinContext<IUserService>(() => {
     return new UserService() as IUserService;
});
Run Code Online (Sandbox Code Playgroud)

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

IUserService userService = context.Get<IUserService>(???);
Run Code Online (Sandbox Code Playgroud)

Ser*_*diy 3

您可以使用以下方法typeof获取key参数:

HttpContext.GetOwinContext().Get<ApplicationDbContext>(typeof(ApplicationDbContext).ToString());
Run Code Online (Sandbox Code Playgroud)

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