7
\$\begingroup\$

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 ?

\$\endgroup\$
  • \$\begingroup\$ Would AppDbContext fail (throw exception) if the SessionContext is not set? Is ISessionContext like a current user session? +1 for SimpleInjector - my current favourite DI Container. \$\endgroup\$ – Andez Mar 18 '18 at 21:29
1
\$\begingroup\$

There is any specific need to register those per single request ?

  • IUserStore
  • IRoleStore
  • AppRoleManager
  • AppRoleManager
  • AppRoleManager

Weird implementations apart they should be fine as "per application" removing a lot of overhead

Also, you probably can add the sessioncontext to AppDbContext constructor and make a single registration

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.