Zak elouarak
Zak elouarak

Reputation: 11

Extension Method C# ASP.NET Core

I have this extension method and I have a problem when I call it in my startup class:

public static class ServiceExtensions
{
        public static void ConfigureMySqlContext(this IServiceCollection services, IConfiguration config)
        {
            var connectionString = config["mysqlconnection:connectionString"];
            services.AddDbContext<RepositoryContext>(o => o.UseSqlServer(connectionString));
        }
}

And this in startup class - I get an error to add IServiceCollection (.NET Core 6)

ServiceExtensions.ConfigureMySqlContext(builder.Configuration);

Upvotes: 1

Views: 1959

Answers (1)

Marco
Marco

Reputation: 23937

You are calling this extension in the wrong way. Since it is an "Extension" method, you need to invoke it on the concrete object, it is extending. By using the this keyword, you are extending the type you are invoking this method on by a specific functionality, without deriving from with a custom type.

services.ConfigureMySqlContext(builder.Configuration);

or, if you are basing your code off of the .net 6 minimal templates:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.ConfigureMySqlContext(builder.Configuration);

var app = builder.Build();

Documentation: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Upvotes: 7

Related Questions