简体   繁体   中英

DotNet 6 - how to create class library for service extensions

I have 2 different Web APIs in Dot net 6. Each web API is a separate project in a Visual studio 2022 solution.

I need to setup middleware services in both API sin program.cs separately. I would like to create a separate class library and reuse the logic in both

These are the steps I took to implmenent AddCors

  1. following code is needed in both APIs in Program.cs
builder.Services.AddCors(o => 
    o.AddPolicy("AllowOrigins", builder =>
    {
        builder.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader();
    }));
  1. In order to avoid duplication of this logic in both APIs, I created a project “Service extensions” and created following class with logic for cors, so that I can refer to it in both APIs
public static class ServiceExt
{
    public static void addCors(this IServiceCollection services) =>
        services.AddCors(
                // code to add CORS here...         
            );
    }
}

But the issue is it's not recognizing AddCors extension method here..

  1. If this works, I am expecting to have below statements in both APIs in Program.cs
using ServiceExtensions;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.addCors();

Just make sure that you have added the ServiceExtensions project in project references of your API project. 在此处输入图像描述

Then this should work. 在此处输入图像描述

My extension method.

using Microsoft.Extensions.DependencyInjection;

namespace ServiceExtensions
{
    public static class ServiceExtensions
    {
        public static IServiceCollection ConfigureCORS(this IServiceCollection services)
            => services.AddCors(options =>
            {
                services.AddCors(o =>
                    o.AddPolicy("AllowOrigins", builder =>
                    {
                        builder.WithOrigins("http://localhost:4200")
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    }));
            });
    }
}

Note : Install and Import the Microsoft.Extensions.DependencyInjection package to access the service collection in ServiceExtensions project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM