大多时候我们采用一下方式进行依赖注入
随着业务的增长,接口跟实现类会越来越多,还需要手动一个个的注册依赖项,有时候会出现忘了写配置,导致程序报错,如果是多人开发,可能还会导致代码冲突,后期维护起来相对来说比较麻烦。
使用Autofac自动注入
1、安装Autofac.Extensions.DependencyInjection
2、修改Program.cs
1 public static IHostBuilder CreateHostBuilder(string[] args) => 2 Host.CreateDefaultBuilder(args) 3 .ConfigureWebHostDefaults(webBuilder => 4 { 5 webBuilder.UseStartup<Startup>(); 6 }) 7 .UseServiceProviderFactory(new AutofacServiceProviderFactory());
3、在Startup.cs中添加ConfigureContainer方法
1 public void ConfigureContainer(ContainerBuilder builder) 2 { 3 builder.RegisterAssemblyTypes(typeof(Program).Assembly) 4 .Where(x => x.Name.EndsWith("service", StringComparison.OrdinalIgnoreCase)).AsImplementedInterfaces(); 5 }
接口层以I开头Service层都要以Service为结尾。
测试:
1 public interface IArticleService 2 { 3 IEnumerable<Article> QueryArticle(); 4 5 int SaveArticle(Article article); 6 7 Article GetArticleById(int Id); 8 9 Page<Article> GetArticlePage(int page, int size, string searchval); 10 11 int DelArticle(int Id); 12 }
1 public class ArticleService : BaseService, IArticleService 2 { 3 /// <summary> 4 /// 查询文章 5 /// </summary> 6 /// <returns></returns> 7 public Article GetArticleById(int Id) 8 { 9 var sql = Sql.Builder.Append("SELECT * FROM MST_ARTICLE WHERE Id=@id", new 10 { 11 id = Id 12 }); 13 return database.SingleOrDefault<Article>(sql); 14 } 15 }
在控制器中注入IArticleService
1 [ApiController] 2 [Route("api/[controller]/[action]")] 3 public class ArticleController : Controller 4 { 5 private IArticleService _articleService; 6 7 private readonly IMapper _mapper; 8 9 public ArticleController(IArticleService articleService, IMapper mapper) 10 { 11 _articleService = articleService; 12 _mapper = mapper; 13 }