依赖注入,带参数注入 [英] Dependency injection, inject with parameters

查看:41
本文介绍了依赖注入,带参数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DI 的 vNext 实现.如何将参数传递给构造函数?例如,我有课:

I'm using vNext implementation of DI. How to pass parameters to constructor? For example, i have class:

public class RedisCacheProvider : ICacheProvider
{
    private readonly string _connectionString;

    public RedisCacheProvider(string connectionString)
    {
        _connectionString = connectionString;
    }
    //interface methods implementation...
}

和服务注册:

services.AddSingleton<ICacheProvider, RedisCacheProvider>();

如何将参数传递给 RedisCacheProvider 类的构造函数?以 Autofac 为例:

How to pass parameter to constructor of RedisCacheProvider class? For example for Autofac:

builder.RegisterType<RedisCacheProvider>()
       .As<ICacheProvider>()
       .WithParameter("connectionString", "myPrettyLocalhost:6379");

推荐答案

您可以提供一个委托来手动实例化您的缓存提供程序或直接提供一个实例:

You can either provide a delegate to manually instantiate your cache provider or directly provide an instance:

services.AddSingleton<ICacheProvider>(provider => new RedisCacheProvider("myPrettyLocalhost:6379"));

services.AddSingleton<ICacheProvider>(new RedisCacheProvider("myPrettyLocalhost:6379"));

请注意,容器不会显式处理手动实例化的类型,即使它们实现了 IDisposable.请参阅有关 服务处置了解更多信息.

Please note that the container will not explicitly dispose of manually instantiated types, even if they implement IDisposable. See the ASP.NET Core doc about Disposal of Services for more info.

这篇关于依赖注入,带参数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆