dotnet core-登录类库

时间:2019-05-31 05:43:31

标签: c# asp.net-core logging .net-core

是否可以在我的ASP.NET Core Web应用程序使用该库的类库中使用Microsoft.Extensions.Logging像在控制器中使用登录(将构造器和框架中的内容通过DI处理)?以及如何实例化类和使用方法?

public class MyMathCalculator
{
    private readonly ILogger<MyMathCalculator> logger;

    public MyMathCalculator(ILogger<MyMathCalculator> logger)
    {
        this.logger = logger;
    }

    public int Fact(int n)
    {
        //logger.LogInformation($"Fact({n}) called.");
        if (n == 0)
        {
            return 1;
        }
        return Fact(n - 1) * n;
    }
}

1 个答案:

答案 0 :(得分:2)

取自previous answer

...这就是依赖注入的魔力,只需让系统为您创建对象,您只需要询问类型即可。

这也是一个大话题,...基本上,您要做的就是将类定义为依赖项,因此,当您请求类时,系统本身会检查依赖项以及该对象的依赖项,直到解析所有的依赖树。

有了这个,如果您的类中又需要一个依赖项,则可以直接添加,但不需要修改所有使用该类的类。

要在控制器中使用此功能,请check the official docs,您只需要将依赖项添加到构造函数中,然后赢取!基本上是两个部分:

添加您的Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}

然后在您的控制器中:

public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }

如果您的图书馆课程在其他项目中,这无异于是,最终,您将把课程添加到启动中,这就是asp net知道要加载什么的方式。

如果您希望代码干净,可以使用Extension方法对所有声明和仅调用services.AddMyAwesomeLibrary()进行分组,例如:

在您的awesomeLibraryProject中:

public static class MyAwesomeLibraryExtensions
{
    public static void AddMyAwesomeLibrary(this IServiceCollection services)
    {
        services.AddSingleton<SomeSingleton>();
        services.AddTransient<SomeTransientService>();
    }
}

在您的创业公司中

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddMyAwesomeLibrary();
    }
相关问题