【问题标题】:C# .NET Core: how to implement dependency injection in my own classes [duplicate]C# .NET Core:如何在我自己的类中实现依赖注入 [重复]
【发布时间】:2019-10-24 02:09:02
【问题描述】:

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

例如,如果有一个“FromDI”属性可以使用如下:

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

非常感谢, 斯特凡诺

【问题讨论】:

  • 对不起,我没有使用fabric,我想在一个简单的控制台应用程序中使用di,没有网络应用程序
  • 最简单的方法是定义一个 DI 容器。一旦定义了 DI 容器(Castle Windsor;Autofac;Unity;MEF...),您应该注册类和接口,然后才能在项目中应用 DI。

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


【解决方案1】:

我自己的类可以有相同的行为吗?

是的,这是内置的。

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

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

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

【讨论】:

【解决方案2】:

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

我正在使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2020-10-13
    • 1970-01-01
    • 2020-09-20
    • 2016-05-22
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多