我正在MVC 6中构建一次性应用程序,并尝试使用不同的依赖架构.
我面临的问题是如何创建MyAppContext特定于应用程序的自定义对象.这将需要HttpContext来自数据库的一些信息和来自数据库的一些信息,并且将是针对特定于应用程序的属性的请求范围的存储库.我想将实例传递HttpContext给' MyAppContext' 的构造函数.
我已成功使用DI 创建了一个DataService带有IDataService接口的对象,这可以正常工作.与'MyAppContext'类的不同之处在于它在构造函数中有两个参数 - DataService'和' Microsoft.AspNet.Http.HttpContext.这是MyAppContext类:
public class MyAppContext : IMyAppContext
{
    public MyAppContext(IDataService dataService, HttpContext httpContext)
    {
       //do stuff here with the httpContext
    }
}
Run Code Online (Sandbox Code Playgroud)
在启动代码中,我注册了DataService实例和MyAppContext实例:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        //adds a singleton instance of the DataService using DI
        services.AddSingleton<IDataService, DataService>();
        services.AddScoped<IMyAppContext, MyAppContext>();    
    }
    public void Configure(IApplicationBuilder app)
    {
        app.UseErrorPage();
        app.UseRequestServices();
        app.UseMvc(routes => /* routes stuff */);
    }
Run Code Online (Sandbox Code Playgroud)
我希望HttpContext …
c# asp.net-mvc dependency-injection asp.net-core-mvc asp.net-core
我希望IUserRepository具有多个实现,每个实现都可以使用MongoDB或任何SQL数据库的数据库类型.为此,我有ITenant接口,它具有连接字符串和其他租户配置.租户已被注入IUserRepository MongoDB或任何SQLDB实现.我需要知道的是如何正确地更改注入的存储库以选择租户的数据库.
接口
public interface IUserRepository 
{
    string Login(string username, string password);
    string Logoff(Guid id);
}
public class User
{
    public Guid Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}
public interface ITenant
{
    string CompanyName { get; }
    string ConnectionString { get; }
    string DataBaseName { get; }
    string EncriptionKey { get; } …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何访问ASP.NET控制器之外的当前登录用户名.
例如,我试图这样做:
设置跟踪实体的跟踪DbContext.
这是我的,ApplicationDbContext但我一直收到错误的说法_httpContextAccessor是null:
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
    : base(options)
{
    _httpContextAccessor = httpContextAccessor;
}
Run Code Online (Sandbox Code Playgroud) c# entity-framework asp.net-core-mvc asp.net-core asp.net-core-1.0
在MVC 5中,您可以使用HttpContext进行访问HttpContext.Current。访问当前HttpContext或更好的仅当前的首选方式是RouteContext什么?
我正在编写一个服务来访问有关当前用户的信息.
目前我通过参数将控件中的User属性传递给我的逻辑类,并以这种方式使用ClaimsPrincipal.
我知道通常有一些方法可以全局访问当前用户(例如,在以前的版本中使用HttpContext.Current.User),那么MVC 6中当前的等价物是什么?
这个问题的答案解释了ClaimsPrincipal.Current不是线程安全的,因此不能替代HttpContext.Current.User