Я изучал возможности использования сборок в Asp.net core и наткнулся на одну проблему. При попытке вызвать метод точки входа в приложение, использующее контекст данных для связи с БД выкидывает ошибку. Контекст оформлен как сервис.
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'TestMVC1.Models.MobileContext' while attempting to activate 'TestMVC1.Controllers.HomeController'.
InvalidOperationException: Unable to resolve service for type 'TestMVC1.Models.MobileContext' while attempting to activate 'TestMVC1.Controllers.HomeController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Как правильно использовать БД внутри загружаемой сборки?
Загрузка сборки
public void ConfigureServices(IServiceCollection services)
{
executableLocation = Assembly.GetEntryAssembly().Location;
var path = Path.Combine(Path.GetDirectoryName(executableLocation), "Plugins");
var assemblies = Directory
.GetFiles(path, "*.dll", SearchOption.AllDirectories)
.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath)
.ToList();
path = Path.Combine(path, "TestMVC1.dll");
var alc = new TestAssemblyLoadContex();
Assembly a = alc.LoadFromAssemblyPath(path);
var b = a.GetTypes();
services.AddMvc().AddApplicationPart(a).AddRazorOptions(
o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(a, a.GetName().Name));
}
);
a.EntryPoint.Invoke(null, new Object[] { null });
}
Использование сервиса с контекстом БД
private MobileContext db;
public HomeController(MobileContext context)
{
db = context;
}
Контекст данных
public class MobileContext : DbContext
{
public DbSet<Phone> Phones { get; set; }
public MobileContext(DbContextOptions<MobileContext> options)
: base(options)
{
Database.EnsureCreated();
}
}