I configure asp.net identity using Simple Injector
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
//Identity
container.RegisterPerWebRequest<AppDbContext>();
container.RegisterPerWebRequest<IUserStore<User, int>>(() => new UserStore<User, Role, int, UserLogin, UserRole, UserClaim>(new AppDbContext()));
container.RegisterPerWebRequest<IRoleStore<Role, int>>(() => new RoleStore<Role, int, UserRole>(new AppDbContext()));
container.RegisterPerWebRequest<AppRoleManager>();
container.RegisterPerWebRequest<AppUserManager>();
container.RegisterPerWebRequest<AppSignInManager>();
container.RegisterPerWebRequest(() =>
{
if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying)
{
return new OwinContext().Authentication;
}
return HttpContext.Current.GetOwinContext().Authentication;
});
And configure a property injection for BaseController
and my DbContext
My BaseController
public class BaseController : Controller
{
public ISessionContext SessionContext { get; set; }
}
My register in simple injector
container.Register<ISessionContext,ClaimsSessionContext>();
container.RegisterInitializer<BaseController>(ctrl =>
{
ctrl.SessionContext = container.GetInstance<ISessionContext>();
});
My DbContext
public class AppDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
{
public ISessionContext SessionContext { get; set; }
public AppDbContext()
: base("AppConnection")
{
}
public static AppDbContext Create()
{
return new AppDbContext();
}
And my simple injector register for property injection
container.RegisterInitializer<AppDbContext>(db =>
{
db.SessionContext = container.GetInstance<ISessionContext>();
});
I wonder if there would be no problem injecting SessionContext property next to my DbContext, for every request it is also instantiated
Suggestions? This ok ?
AppDbContext
fail (throw exception) if theSessionContext
is not set? Is ISessionContext like a current user session? +1 forSimpleInjector
- my current favouriteDI Container
. \$\endgroup\$