public sealed class SessionContext
{
private ISession httpContext;
public SessionContext(ISession httpContext)
{
this.httpContext = httpContext;
}
public string UserType
{
get
{
return httpContext.GetString("_UserType");
}
set
{
httpContext.SetString("_UserType", value);
}
}
...... More properties .....
}
public class HomeController : Controller
{
private AppSettings _appSettings;
private SessionContext session = null;
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession httpContext => _httpContextAccessor.HttpContext.Session;
//I don't like this constructor as it is getting initialize or every controller call.
public HomeController(IOptions<AppSettings> myAppSettings, IHttpContextAccessor httpContextAccessor)
{
_appSettings = myAppSettings.Value;
_httpContextAccessor = httpContextAccessor;
appSettings = new AppSettings(_appSettings); //Should initialize only once.
session = new SessionContext(httpContext);
}
}
我对...有疑问
从问题转到答案:
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddSingleton<SessionContext, SessionContext>(); //calling the extension class to instantiate the classes which we require earlier. services.AddMyProjectHelper(Configuration) }
创建了一个扩展类...初始化支持类
public static class MyProjectHelperExtensions { public static IServiceCollection AddMyProjectHelper(this IServiceCollection services, IConfiguration configuration) { var section = configuration.GetSection("AppSettings"); // we first need to create an instance var settings = new AppSettings(); // then we set the properties new ConfigureFromConfigurationOptions<AppSettings>(section).Configure(settings); var session = services.BuildServiceProvider().GetService<SessionContext>(); // then we register the instance into the services collection services.AddSingleton<MyProjectHelper>(new MyProjectHelper(settings, session)); return services; } }
最后,控制器ctor使用DI作为所需的类。现在我避免了支持类的冗余初始化。
public SecurityController(MyProjectHelper objHelper, SessionContext sessionContext) { session = sessionContext; projectHelper = projectHelper ?? objHelper; }
现在,我能够共享我在支持类中设置的会话变量
private SessionContext session = null; public HomeController(SessionContext sessionContext) { session = sessionContext; } [Authorize] public IActionResult Index() { if (session.CurrEmployee != null) { ViewBag.Name = (session.CurrEmployee.FirstName + " " + session.CurrEmployee.LastName); return View(); } }