标签: ambientcontext

使用静态工厂Func <T>为ASP.NET应用程序创建"Ambient Context"(UserContext)

我发现几乎每个类(控制器,视图,HTML帮助程序,服务等)都需要当前登录的用户数据.所以我想创建一个"Ambient Context"而不是直接注入IUserService或User.

我的方法看起来像那样.

public class Bootstrapper
{
    public void Boot()
    {
        var container = new Container();
        // the call to IUserService.GetUser is cached per Http request
        // by using a dynamic proxy caching mechanism, that also handles cases where we want to 
        // invalidate a cache within an Http request
        UserContext.ConfigureUser = container.GetInstance<IUserService>().GetUser;
    }
}

public interface IUserService
{
    User GetUser();
}

public class User
{
    string Name { get; set; }
}

public class UserContext : AbstractFactoryBase<User>
{
    public …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc dependency-injection ambientcontext

11
推荐指数
1
解决办法
2905
查看次数

使用通用 IHostBuilder 时访问 IServiceProvider

IHostBuilder我在 .NET Core 2.1 控制台应用程序中使用。主要看起来像这样:

    public static async Task Main(string[] args)
    {
        var hostBuilder = new HostBuilder()
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureServices(services =>
            {
                // Register dependencies
                // ...

                // Add the hosted service containing the application flow
                services.AddHostedService<RoomService>();
            });

        await hostBuilder.RunConsoleAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

之前,使用IWebHostBuilder,我有Configure()让我这样做的方法:

public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment environment)
{
    // Resolve something unrelated to the primary dependency graph
    var thingy = applicationBuilder.ApplicationServices.GetRequiredService<Thingy>();
    // Register it with the ambient context
    applicationBuilder.AddAmbientThingy(options => options.AddSubscriber(thingy));

    // Use …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection ambientcontext .net-core .net-core-2.1

5
推荐指数
1
解决办法
3627
查看次数