Home > Blockchain >  How to inject custom service on startup in .NET Core 5
How to inject custom service on startup in .NET Core 5

Time:07-24

I want to read my data from database and control it, and I need to do this in the request pipeline at startup.

So I have to do dependency injection at startup.

This is my (DI)

public Startup(IConfiguration configuration,IAuthHelper authHelper)
{
        Configuration = configuration;
        AuthHelper = authHelper;
}

public IConfiguration Configuration { get; }
public IAuthHelper AuthHelper;

I encounter this error

An error occurred while starting the application. InvalidOperationException: Unable to resolve service for type 'Laboratory.Core.Services.Interfaces.IAuthHelper' while attempting to activate 'Laboratory.Startup'.

I used service like this

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var siteDirectory = AuthHelper.GetSiteSetting().MediaPath;
    var fileServerOptions = new FileServerOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine
                (env.WebRootPath, $@"{siteDirectory}User Picture\")),
            RequestPath = "/ServerFiles"
        };

    app.UseFileServer(fileServerOptions);
}

This is my service

public class AuthHelper : IAuthHelper
{
    private readonly LaboratoryContext _context;
    private readonly IRazorPartialToStringRenderer _renderer;
    private readonly IHttpContextAccessor _httpContext;
    private readonly IHttpClientFactory _clientFactory;
   
    public AuthHelper(LaboratoryContext context, IRazorPartialToStringRenderer renderer, IHttpContextAccessor httpContext, IHttpClientFactory clientFactory)
    {
        _context = context;
        _renderer = renderer;
        _httpContext = httpContext;
        _clientFactory = clientFactory;
    }

    public TableSiteSetting GetSiteSetting()
    {
        try
        {
            return _context.TableSiteSettings.AsNoTracking().FirstOrDefault();
        }
        catch (SqlException)
        {
            return new TableSiteSetting() { StaticIp = "ServerConnectionError" };
        }
        catch (Exception)
        {
            return new TableSiteSetting() { StaticIp = "ServerError" };
        }
    }
}

Thanks for any help.

CodePudding user response:

Your service can't be injected in Startup constructor because it has not been added yet to the dependency injection container. But you can inject it to the Configure method.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthHelper authHelper)
{
    ...
}

I assume you have already registered the service in ConfigureServices

services.AddSingleton<IAuthHelper, AuthHelper>(); // Or scoped/transient depends what your service does.

CodePudding user response:

You can get dbcontext service in program.cs and do what ever you like to your database data. for example I use this approach to seed my database:

var host = CreateHostBuilder(args).Build();         


using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();

    await ApplicationDbContextSeed.SeedSampleDataAsync(context)
}
            

host.Run();

  • Related