C#.NET Core:如何在我自己的类中实现依赖项注入

时间:2019-06-09 09:27:32

标签: c# dependency-injection .net-core

我知道在.net中使用标准依赖项注入,可以为控制器类自动实例化MVC项目参数的构造函数。我的问题是:我自己的班级是否可能有相同的行为?

例如,如果有一个“ FromDI”属性可以按如下所述使用,那就太好了:

public class MyClass {
   public MyClass([FromDI] IInputType theInput = null) {
     // i would like theInput is populated automatically from DI system 
   }
}

非常感谢, 斯特凡诺

2 个答案:

答案 0 :(得分:3)

  

我自己的类是否可能具有相同的行为?

是的,它是内置的。

您的类需要进行注册和自身注入,然后可以使用构造函数注入而无需任何属性。

  

想在简单的控制台应用程序中使用di,无需在网络应用程序中使用

这意味着您将必须设置ServiceProvider和范围。这些东西已经由ASP.Net Core提供。

答案 1 :(得分:1)

为简单起见,我创建以下方案来向您展示如何在简单的控制台应用程序中使用依赖项注入。

我正在使用 HttpClient httpClient = HttpClient.create() .tcpConfiguration(client -> client .doOnConnected(conn -> conn .addHandlerLast(new ReadTimeoutHandler(readtimeout)) .addHandlerLast(new WriteTimeoutHandler(writetimeout))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectiontimout)); return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .baseUrl(cartDataUrl) .build(); -安装NuGet:Castle Project

我有以下界面:

Install-Package Castle.Core -Version 4.4.0

除类之外,还实现了接口:

public interface ITranslate
{
    string GetMenu();
}

public interface IFood
{
    string GetFood();
}

如果我将所有内容放到public class FrenchCuisine : IFood { public string GetFood() { return "Soupe à l'oignon"; } } public class ComidaBrasileira : IFood { public string GetFood() { return "Feijoada"; } } public class FrenchTranslator : ITranslate { private readonly IFood food; public FrenchTranslator(IFood food) { this.food = food; } public string GetMenu() { return this.food.GetFood(); } } public class PortugueseTranslator : ITranslate { private readonly IFood food; public PortugueseTranslator(IFood food) { this.food = food; } public string GetMenu() { return this.food.GetFood(); } } 中:

Console Application

预期结果

using Castle.Windsor;
using System;
using Component = Castle.MicroKernel.Registration.Component;

namespace StackoverflowSample
{
  internal class Program
  {
    //A global variable to define my container.
    protected static WindsorContainer _container;

    //Resolver to map my interfaces with my implementations
    //that should be called in the main method of the application.
    private static void Resolver()
    {
        _container = new WindsorContainer();

        _container.Register(Component.For<IFood>().ImplementedBy<FrenchCuisine>());
        _container.Register(Component.For<IFood>().ImplementedBy<ComidaBrasileira>());

        _container.Register(
            Component.For<ITranslate>().ImplementedBy<FrenchTranslator>().DependsOn(new FrenchCuisine()));
    }

    private static void Main(string[] args)
    {
        Resolver();

        var menu = _container.Resolve<ITranslate>();
        Console.WriteLine(menu.GetMenu());
        Console.ReadKey();
    }
  }
}