44

NET Core 3.0 AutoFac替换内置DI的新姿势

 4 years ago
source link: https://www.tuicool.com/articles/ZveiYrF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

.NET Core 3.0 和 以往版本不同,替换AutoFac服务的方式有了一定的变化,在尝试着升级项目的时候出现了一些问题。

原来在NET Core 2.1时候,AutoFac返回一个 IServiceProvider 参数注入到ConfigureServices .NET Core 服务中,基本大痣是这样做的。

首先我们需要一个重写 Autofac.Module 的方法,这将用于将我们  Register [数据访问层] 以及   Services [逻辑层] 的注册。

VbUBFbA.png!web

随后,将.NET Core的ConfigureServices方法的返回值改成IServiceProvider,这将用于注入你的服务。

V7RJBfq.png!web

上面的代码中我们调用了 ForRegisterAutoFac 我们自定义的方法,这将我们定义的策略和AutoFac 一起替换内置DI.

n2AzuaF.png!web

在API层,我们依赖注入Service,这样我们.NET Core2.1基本的AutoFac就实现了。

feANFnM.png!web

就现在我们说一说.NET Core3.0 和 以往版本的区别。我将所有项目以及依赖项全部改成3.0版本,就现在启动,你会发现意想不到的事情。

VN7fMnm.jpg!web

啥?你说啥?弄萨累? 咋不管用了嘞?

UZzuU3A.png!web

经过看了官方文档,才知道..NET Core 3.0 引入了具有强类型容器配置的功能。它提供了 ConfigureContainer 方法,您可以在其中使用Autofac来注册事物,而不必通过  ServiceCollection 来注册事物。so....好吧!在.NET Core3.0 将如何配置。

首先我们需要在 Program.cs 中修改服务工厂,内置是  ServiceProviderFactory 的,我们将要指定为:  AutofacServiceProviderFactory

EzU3E37.png!web

现在需要在 Startup.cs 中添加方法  ConfigureContainer ,并添加以下代码。

zUrYNf2.png!web

然后大功告成,启动再也没问题了~。

aUZbQff.png!web

 Github地址:https://github.com/zaranetCore/Blog.DDD.Solucation
 
 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK