0

I am using a Blazor WASM Application with .NET6

Whenever I try to use my service class it gives me this error 'Unable to resolve service for type 'Persistence.Data.DataContext' while attempting to activate 'Services.Customers.CustomerService'.'

Heres my classes (simplified):

Persistence.Data.DataContext:

public class DataContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    
    
    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        // Add configurations
        base.OnModelCreating(builder);
        builder.ApplyConfiguration(new CustomerConfiguration());
    }
}

Services.Customers.CustomerService:

public class CustomerService : ICustomerService
{
    private readonly DataContext _dbContext;

    public CustomerService(DataContext dbContext)
    {
        this._dbContext = dbContext;
    }

    //...
}

Client.Program.cs:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddMudServices();

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

builder.Services.AddScoped<ICustomerService, CustomerService>();

await builder.Build().RunAsync();

Server.Startup.cs:

public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        [Obsolete]
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DataContext"));
            
            services.AddDbContext<DataContext>(options =>
                options.UseSqlServer(builder.ConnectionString)
                    .EnableSensitiveDataLogging(Configuration.GetValue<bool>("Logging:EnableSqlParameterLogging")));
           
            services.AddControllersWithViews();

            services.AddScoped<DataInitializer>();

            services.AddRazorPages();

            services.AddScoped<ICustomerService, CustomerService>();
        }
        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataInitializer dataInitializer)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Vic API"));

                dataInitializer.InitializeData();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }

Thanks in advance

JanneVS
  • 21
  • 1

1 Answers1

1

WebAssemblyHostBuilder projects don't use Startup.cs (and its Configure and ConfigureServices).

Blazor WebAssembly 3.2.0 Preview 1 release now available says:

  • Move the root component registrations in the Blazor WebAssembly client project from Startup.Configure to Program.cs by calling builder.RootComponents.Add(string selector).
  • Move the configured services in the Blazor WebAssembly client project from Startup.ConfigureServices to Program.cs by adding services to the builder.Services collection.
  • Remove Startup.cs from the Blazor WebAssembly client project.

ASP.NET Core Blazor Server with Entity Framework Core (EF Core) says:

The recommended approach to create a new DbContext with dependencies is to use a factory. EF Core 5.0 or later provides a built-in factory for creating new contexts.

and the example app at https://github.com/dotnet/blazor-samples/blob/main/6.0/BlazorServerEFCoreSample/BlazorServerDbContextExample/Program.cs does the registration direcly in main:

builder.Services.AddDbContextFactory<ContactContext>(opt => ...
tymtam
  • 31,798
  • 8
  • 86
  • 126