C#?利用Autofac批量接口注入依賴的問(wèn)題小結(jié)
背景:
本人在一位大佬的Colder框架中看到了這個(gè)接口注入,然后呢就想學(xué)習(xí)一下ioc思想與di設(shè)計(jì)模式。此寫法給我的感覺(jué)就是
非常的 優(yōu)雅 ,優(yōu)雅永不過(guò)時(shí)。關(guān)于接口注入具體是什么可以最后推薦的地址。話不多說(shuō),開(kāi)擼。
安裝:
打開(kāi)nuget管理工具,將我下面標(biāo)紅色的包都進(jìn)行安裝(注:千萬(wàn)別安裝錯(cuò)了,按照名字不差的安裝)

使用:
我們新建一個(gè)DI的文件夾,在文件夾中增加一個(gè)接口:IDependency.cs
namespace Coldairarrow
{
/// <summary>
/// 注入標(biāo)記
/// </summary>
public interface IDependency
{
}
}
先不要問(wèn)問(wèn)什么后面會(huì)解釋。
后面:其實(shí)。。就是這個(gè)依賴注入的一個(gè)原理吧。根據(jù)這個(gè)接口去找依賴的實(shí)現(xiàn)。
推薦去這個(gè)地址看一下:http://m.fzitv.net/article/206284.htm
好了,繼續(xù)分別新建Student.cs,StudentRepository.cs,IStudentRepository.cs三個(gè)類。StudentRepository.cs里面的具體業(yè)務(wù)根據(jù)需要自行修改,這里是為了測(cè)試使用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ByzkApi
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Graduation { get; set; }
public string School { get; set; }
public string Major { get; set; }
}
}
using Coldairarrow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ByzkApi
{
public class StudentRepository : IStudentRepository,IDependency
{
public Student Add(Student item)
{
throw new NotImplementedException();
}
public bool Delete(int id)
{
throw new NotImplementedException();
}
public Student Get(int id)
{
return new Student() { Name = "張三" };
}
public IEnumerable<Student> GetAll()
{
throw new NotImplementedException();
}
public bool Update(Student item)
{
throw new NotImplementedException();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ByzkApi
{
public interface IStudentRepository
{
IEnumerable<Student> GetAll();
Student Get(int id);
Student Add(Student item);
bool Update(Student item);
bool Delete(int id);
}
}
注意:這里好好看一下StudentRepository 是實(shí)現(xiàn)了兩個(gè)接口分別是 IStudentRepositoryIDependency(注入標(biāo)記)
最關(guān)鍵的地方來(lái)了,我們打開(kāi)項(xiàng)目啟動(dòng)的函數(shù)Application_Start,然后注入一下接口依賴。
using Autofac;
using Autofac.Extras.DynamicProxy;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using ByzkApi.Controllers;
using ByzkApi.Interface;
using Coldairarrow;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace ByzkApi
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//初始化Autofac
InitAutofac(GlobalConfiguration.Configuration);
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
private void InitAutofac(HttpConfiguration config)
{
var builder = new ContainerBuilder();
var baseType = typeof(IDependency);
//可以進(jìn)行篩選如: Where(x => x.FullName.Contains("Coldairarrow"))
var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>()
.ToList();
//自動(dòng)注入IDependency接口,支持AOP,生命周期為InstancePerDependency
builder.RegisterAssemblyTypes(assemblys.ToArray())
.Where(x => baseType.IsAssignableFrom(x) && x != baseType)
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerDependency()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(Interceptor));
//注冊(cè)Controller
builder.RegisterControllers(assemblys.ToArray())
.PropertiesAutowired();
builder.RegisterApiControllers(assemblys.ToArray()).PropertiesAutowired();
//AOP
builder.RegisterType<Interceptor>();
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
AutofacHelper.Container = container;
}
}
}
到此為止就已經(jīng)注入完成了~
使用:
這個(gè)接口注入好了之后可以在普通的Controller使用,也可以在apiController進(jìn)行使用,分別看一下效果,結(jié)束。
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ByzkApi.Controllers
{
public class HomeController : Controller
{
readonly IStudentRepository repository;
//構(gòu)造器注入
public HomeController(IStudentRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var a = repository.Get(1);
ViewBag.Title = a.Name;
return View();
}
}
}

ApiController:(如果想要多個(gè)接口只需要實(shí)現(xiàn)接口的時(shí)候進(jìn)行繼承IDependency就可)
using ByzkApi.Interface;
using Coldairarrow.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace ByzkApi.Controllers
{
public class TestApiController : ApiController
{
readonly IStudentRepository repository;
public ITest _test { get; }
//構(gòu)造器注入
public TestApiController(IStudentRepository repository, ITest test)
{
this.repository = repository;
_test = test;
}
[HttpGet]
public DataTable test(string sql)
{
repository.Get(1);
var data = _test.GetTest("sql 語(yǔ)句");
//repository.GetTest(sql);
return data;
}
}
}

到此這篇關(guān)于C# 利用Autofac批量接口注入依賴的文章就介紹到這了,更多相關(guān)C# Autofac批量注入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Treeview動(dòng)態(tài)添加用戶控件傳值和取值的實(shí)例代碼
今天做了很好玩的樹(shù),是treeview與用戶控件之間進(jìn)行交互先看效果:2013-04-04
C# 靜態(tài)變量與靜態(tài)方法實(shí)例研究
寫了一個(gè)翻譯英漢單詞辭典的小程序,發(fā)現(xiàn)在調(diào)用幾千次的時(shí)候速度很慢2011-11-11
Unity3D舊電視濾鏡shader的實(shí)現(xiàn)示例
這篇文章主要介紹了Unity3D舊電視濾鏡shader的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
C#集合根據(jù)對(duì)象的某個(gè)屬性進(jìn)行去重的代碼示例
當(dāng)根據(jù)對(duì)象的Name屬性進(jìn)行去重時(shí),你可以使用以下三種方法:使用Distinct方法和自定義比較器、使用LINQ的GroupBy方法,以及使用HashSet,下面給大家介紹C#集合根據(jù)對(duì)象的某個(gè)屬性進(jìn)行去重的代碼示例,感興趣的朋友一起看看吧2024-03-03
在類庫(kù)或winform項(xiàng)目中打開(kāi)另一個(gè)winform項(xiàng)目窗體的方法
這篇文章主要介紹了在類庫(kù)或winform項(xiàng)目中打開(kāi)另一個(gè)winform項(xiàng)目窗體的方法,可以實(shí)現(xiàn)Winform項(xiàng)目間窗體的調(diào)用,在進(jìn)行Winform項(xiàng)目開(kāi)發(fā)中非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-11-11
C#機(jī)器入門學(xué)習(xí)之判斷日?qǐng)?bào)是否合格詳解
這篇文章主要給大家介紹了關(guān)于C#機(jī)器入門學(xué)習(xí)之判斷日?qǐng)?bào)是否合格的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用c#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

