Не удается создать объект типа "AppDbContext" во время создании миграции
В PowerShell ввожу:
dotnet ef migrations add _initial
Получаю:
Build started...
Build succeeded.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebApplication3.Domain.Repositories.DataManager Lifetime: Transient ImplementationType: WebApplication3.Domain.Repositories.DataManager': A suitable constructor for type 'WebApplication3.Domain.Repositories.DataManager' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.)
Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Проблема: Не удается создать миграцию.
AppDbContext.cs
namespace WebApplication3.Domain
{
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<TextField> TextFields { get; set; }
public DbSet<ServiceItem> ServiceItems { get; set; }
...
}
}
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) => Configuration = configuration;
public void ConfigureServices(IServiceCollection services)
{
//подключаем конфиг из appsettings.json
Configuration.Bind("Project", new Config());
//подключаем нужный функционал приложения в качестве сервисов
services.AddTransient<ITextFieldsRepository, EFTextFieldsRepository>();
services.AddTransient<IServiceItemsRepository, EFServiceItemsRepository>();
services.AddTransient<DataManager>();
//Подключаем контекст БД
services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Config.ConnectionString));
//Настройка identity системы
services.AddIdentity<IdentityUser, IdentityRole>(opts =>
{
opts.User.RequireUniqueEmail = true;
opts.Password.RequiredLength = 6;
opts.Password.RequireNonAlphanumeric = false;
opts.Password.RequireLowercase = false;
opts.Password.RequireUppercase = false;
opts.Password.RequireDigit = false;
}).AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
//настраиваем authenitication cookie
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "myCompanyAuth";
options.Cookie.HttpOnly = true;
options.LoginPath = "/account/login";
options.AccessDeniedPath = "/account/accessdenied";
options.SlidingExpiration = true;
});
//добавляем поддержку контроллеров и представлений (MVC)
services.AddControllersWithViews().
//выставляем совместимость с asp.net core 3.0
SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddSessionStateTempDataProvider();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//порядок регистрации middleware очень важен
//в процессе разработки нам важно видеть подробную информацию об ошибках
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
app.UseRouting();
//подключение аутенификации и авторизации
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthentication();
//подключаем поддержку статичных файлов в приложении (css, js e.t.c)
app.UseStaticFiles();
//регистрируем нужные нам маршруты (ендпоинты)
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
}
Ответы (1 шт):
Автор решения: HelloNoWorld
→ Ссылка
Смог решить таким способом:
- Установил EntityFrameworkCore.Tools в NuGet
- В Package Manage Console ввёл команду Add-Migration название миграции. После этого миграция создалась.
Надеюсь твоё решение было без установки дополнительного пакета и с помощью ввода другой команды в Power Shell.
А теперь я смог решить проблему нормальным способом. У меня в строке подключения была ошибка, проверь её внимательно.