如何在 .net 4.7 项目中使用 Unity 容器解析 EF Core 上下文



我有一个问题,我需要将我的项目升级到最新版本的 .NET,目前所有项目都是使用实体框架 6 的 .NET 4.7 或 .NET 标准 2.0,然后通过 WCF 服务公开,该服务通过 Unity 获取其实例化。

计划是从 EF 6 升级到 EF Core 3 开始,然后使用控制反转将其解耦,以便能够在需要时更改基础数据访问,这已经开始,所有存储库调用都引用接口 IMyDbContext,似乎没问题。

现在我有一个问题,即如何从WCF应用程序中的Unity容器解析IMyDbContext,因为它是.Net 4.7,并且包含MyDbContext的项目是.net core 3。

任何指针/参考将不胜感激。

对于具有多个项目的解决方案,一些在.Net Framework上,一些在.Net Core上,我使用如下内容:

public class MyContext : DbContext
{
static MyContext()
{
Database.SetInitializer<MyContext>(null);
}
[InjectionConstructor] //Used to specify the constructor to Unity
public MyContext() 
: base("Name=MyContext")
{
}
public MyContext(string connectionString) //Used to resolve de dependency in .net Core
: base(connectionString)
{
}   
}

启动.cs在.Net Core MVC项目中

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<MyContext>(_ => new MyContext(Configuration.GetConnectionString("DefaultConnection")));
}

在.Net Framework项目中,项目作为参数传递给存储库IDoStuffRepo,该存储库注册如下:

public override void Initialize(){
this.Container.RegisterType<IDoStuffRepo, DoStuffRepo>(new DisposableTransientLifetimeManager());
}

最新更新