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



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

例如,最好有一个"FromDI"属性,可以按如下方式使用:

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

多谢Stefano

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

是的,这是内置的。

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

想要在简单的控制台应用中使用 DI,没有 Web 应用

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

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

我正在使用Castle Project - 安装 NuGet: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();
    }
  }
}

预期成果

Soupe à l'oignon

最新更新