首页 > 解决方案 > How do I inject a DBContext into a service in Startup?

问题描述

I have a service that I want to use in a .Net core Blazor app.

The service uses a context that I want to pass to it.

public class MyService
{
    public AddDbContextContext { get; set; }

    public MyService(AddDbContext mycontext)
    {
        Context = mycontext;
    }
}

In Startup, I create the context that I want the service to use:

public void ConfigureServices(IServiceCollection services)
{
        //configure the context 
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("HIDDEN"));

        //how do I pass the context?
        services.AddSingleton<MyService>();
}

How do I pass the context to service?

标签: asp.netblazor

解决方案


How do I pass the context to service?

You don't pass the context to the service. It is automatically done when the DI container creates your service.

Since your DBContext is named ApplicationDbContext, your service should look like this:

public class MyService
{
    private ApplicationDbContext _context;

    public MyService(ApplicationDbContext context)
    {
        _context = context;
    }
}

Note: You can only use DBContext in Blazor Server App

Note: I've only answered your question here. But it's very likely you'll have issues with the DBContext, depending on what you do in your service. You should consult the documents how to use the DBContext in Blazor, particularly, why and how you should use AddDbContextFactory


推荐阅读