如何在Unity容器中注册Func <task <t >>?

时间:2018-10-25 21:13:04

标签: .net asp.net-mvc dependency-injection .net-core unity-container

我有ASP.NET Core应用程序。我能够按照以下方式在startup.cs中注册Func<Task<T>>

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped(factory =>
        {
            Func<Task<SftpClient>> provider = async () =>
            {
                using (var serviceScope = factory.CreateScope())
                {
                    using (var dbContext = serviceScope.ServiceProvider.GetService<MyDBContext>())
                    {
                        // make async call to dbContext to get information required for SFTPClient
                        // then create instance of SFTPClient

                        var sftpClient = new SftpClient(host, port,userId,password);
                        return sftpClient;
                    }
                }
            };
            return provider;
        });
    }

.Net Core应用程序运行正常。

现在,我想使用Unity容器在经典ASP.NET中执行相同的操作。这是我当前在ASP.NET中的代码

    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<DbContext>(new TransientLifetimeManager(), new InjectionFactory(x => CreateDBContext()));
        container.RegisterType<Func<Task<SftpClient>>>(new TransientLifetimeManager(), new InjectionFactory(x => CreateSFTPClient()));
    }

    private static MyDBContext CreateDBContext()
    {
        MyDBContext dbContext = new MyDBContext();
        dbContext.Configuration.LazyLoadingEnabled = false;// turn-off loading on-demand
        dbContext.Configuration.ProxyCreationEnabled = false;// turn-off dynamic proxy class generation
        return dbContext;
    }

    private static Func<Task<SftpClient>> CreateSFTPClient()
    {
        Func<Task<SftpClient>> provider = async () =>
        {
             // How do i get DbContext here?
             // Do i need to create scope like i do in .NET Core?

             var sftpClient = new SftpClient(host, port,userId,password);
              return sftpClient;

        };

        return provider;
    }

如何在async函数中获取DBContext?我是否需要像在.NET Core中那样创建范围?

1 个答案:

答案 0 :(得分:0)

重构CreateSFTPClient以显式注入容器

private static Func<Task<SftpClient>> CreateSFTPClient(IUnityContainer container) {
    Func<Task<SftpClient>> provider = async () => {
        // How do i get DbContext here?
        // Do i need to create scope like i do in .NET Core?
        MyDBContext dbContext = container.Resolve<MyDBContext>();

        //...

        var sftpClient = new SftpClient(host, port, userId, password);
        return sftpClient;
    };
    return provider;
}

然后可以将InjectionFactor表达式参数注入到函数中。

...new InjectionFactory(x => CreateSFTPClient(x)));