如何为Web API项目使用的类库添加依赖注入

huangapple go评论68阅读模式
英文:

How to Add Dependency Injection for a Class Library Used by a Web API Project

问题

我正在尝试在Web API项目和类库(CL)之间使用依赖注入,以便当Web API中的控制器调用CL中的类来执行某些工作时,CL会实例化所有依赖项。

我考虑在Web API中添加对CL的项目依赖,但我已经阅读到我还必须添加程序集,以便在Web API中编译CL,以使依赖注入起作用。这是真的吗?不管怎样,这听起来不像Web API调用CL中的类,而CL只是“让它工作”的方式那么无缝。

我所询问的事情是否已经完成?我对.NET中的依赖注入是新手,对于这种方法,我很难找到正确的教程/博客,所以我愿意研究任何资源。我知道“干净架构”建议使用完全独立的项目来处理跨其他项目的依赖注入,但我计划将这些项目分离成未来的微服务架构(当前使用分层架构,直到我这样做),并且发现很难说服自己采用这种方法的可伸缩性。

如果有关系的话,我正在使用.NET 6.0(其中没有Startup.cs,只有Program.cs而没有函数签名,不确定如何称呼这个)在VS Code上运行Mac OS。

英文:

I'm trying to use dependency injection across a Web API project and a Class Library (CL) so that when a controller in the Web API calls on a class in the CL to do some work, all the dependencies are instantiated by the CL.

I'm thinking I can add a project dependency in the Web API to the CL, but I've read that I also have to add in assemblies so that I can compile the CL in the Web API in order for the dependency injection to work. Is this true? Anyways, it doesn't sound as seamless as the Web API calling the class in the CL and the CL just "makes it work".

Is what I'm asking for been done already? I'm new to dependency injection in .NET and it's been difficult navigating to the correct tutorials/blogs for this kind of approach, so I'm open to any resources that I can research. I know Clean Architecture suggests using a completely separate project to handle the dependency injection across other projects, but I plan to separate these projects into a Microservices architecture in the future (currently using a Layered architecture until I do that) and find it hard to justify to myself the scalability of that approach.

If it at all matters, I'm using .NET 6.0 (where there's no Startup.cs and only the Program.cs without the function signatures, not sure what to call this) on VS Code for Mac OS.

答案1

得分: 2

使用位于不同项目中的服务进行依赖注入并不太困难。

您只需要执行以下几个步骤:

  1. 在Visual Studio中将所需的库添加到您的项目引用中:

  2. 完成上述操作后,您可以像通常一样将服务注册到容器中 - 这里是一个简单的示例Program.cs(没有函数签名,如您所提到的):

注意:您需要自行决定您的服务是应该作为单例、瞬态还是范围内注入,有关该主题的更多信息,请参阅Microsoft Docs。

using MachineData.Domain;

var builder = WebApplication.CreateBuilder(args);

// 将服务添加到容器中。

builder.Services.AddControllers().AddNewtonsoftJson();
// 了解有关配置Swagger/OpenAPI的更多信息,请访问https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGenNewtonsoftSupport();
builder.Services.AddSingleton<HttpClient>() // 在ServiceInLibrary中使用
builder.Services.AddSingleton<ServiceInLibrary>(); // TODO: 在此处插入您的服务
var app = builder.Build();

// 配置HTTP请求管道。
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(opts =>
{
    opts.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

  1. 您也可以像通常一样在位于第二个项目中的服务中使用注入的对象。只需添加一个构造函数参数,就像您已经知道的那样:

当然,您还需要在Program.cs中注册注入的类。

public class ServiceInLibrary
{
    ...
    public ServiceInLibrary(HttpClient http)
    {

    }
    ...
}

希望这回答了您的问题。如果没有,请告诉我。

英文:

Using services located in different projects for dependency injection is not too difficult.

There are only a few things you need to do:

  1. Add the used library to your project references in Visual studio:
    如何为Web API项目使用的类库添加依赖注入

如何为Web API项目使用的类库添加依赖注入

  1. After you have done this, you can register the service to the container as usual - here is a simple example Program.cs (without function signatures, as you mentioned):

NOTE: You need to decide yourself if your service should be injected as a singleton, transient or scoped, see the Microsoft Docs for further information on that topic.

using MachineData.Domain;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers().AddNewtonsoftJson();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGenNewtonsoftSupport();
builder.Services.AddSingleton<HttpClient>() // used in ServiceInLibrary
builder.Services.AddSingleton<ServiceInLibrary>(); // TODO: insert your service here
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(opts =>
{
    opts.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

  1. You can also use injected objects in the service located in your second project as usual. Just add a constructor parameter, as you already know it:

Of course, you need to register the injected class as well in your Program.cs.

public class ServiceInLibrary
{
    ...
    public ServiceInLibrary(HttpClient http)
    {

    }
    ...
}

I hope this answers your question. If not, please let me know.

huangapple
  • 本文由 发表于 2023年6月22日 13:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定