原本想聊一下面試過程的,1個星期面了6家,4家當場給offer,2家技術經過(1家沒下文,1家複試).從中也學習到一些東西,先仍是繼續Coding吧.面試
官網:http://autofac.org/api
下載:Install-Package Autofac -Version 3.5.2瀏覽器
Autofac是輕量級的開源IOC容器,傳說是速度最快的一個,同類的框架還有用過Castle Windsor、StructureMap、Unity、Spring.Net等.框架
本節目錄函數
1.創建項目ui
CA:一個控制檯項目,引用Nuget Autofac包.url
2.創建一個依賴外部的類spa
public class Test { public Test(string str) { Console.WriteLine("hello " + str); } }
3.根據參數名直接注入3d
static void Main(string[] args) {
//建立容器工廠 var builder = new ContainerBuilder(); //註冊Test類型到工廠中 builder.RegisterType<Test>();
//經過工廠建立容器 using (var container = builder.Build()) {
//解析Test並返回Test實例 container.Resolve<Test>(new NamedParameter("str", "world")); } Console.ReadKey(); }
過程:首先須要建立容器工廠,而後將各類類型註冊到工廠中,再建立容器,經過容器實例化對象.
添加1個構造函數
public Test(ISay say) { Console.WriteLine("say:" + say.Get()); }
接口及其實現
public class Say : ISay { public string Get() { return "hello world"; } } public interface ISay { string Get(); }
注入實現(Autofac會自動裝配)
static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<Test>(); builder.RegisterType<Say>().As<ISay>(); using (var container = builder.Build()) { container.Resolve<Test>(); } Console.ReadKey(); }
略做修改
public Test(Say say)//將接口改成指定具體實現類 { Console.WriteLine("say:" + say.Get()); }
此時運行代碼會報錯,由於在容器中咱們只註冊了ISay接口.改成As<Say>或如下方式
builder.RegisterType<Say>().As<ISay>().AsSelf();
對象生命週期
註冊到工廠的類型默認都調用InstancePerDependency方法.實現每一個依賴都建立1個新實例
單例模式:
builder.RegisterType<Test>().SingleInstance();
須要引用Nuget Autofac.Configuration包
註冊類型代碼
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
App.config
<configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" /> </configSections> <autofac defaultAssembly="CA"> <components> <component type="CA.Say, CA" service="CA.ISay" /> <component type="CA.Say, CA" service="CA.Say" /> </components> </autofac>
service至關於As<T>中的T
1.Install-Package Autofac.Mvc5
2.Application_Start事件添加此方法
protected void Application_Start(object sender, EventArgs e) { #region 1.MVC Autofac注入 var builder = new ContainerBuilder(); //類名.EndsWith("Controller") builder.RegisterControllers(Assembly.GetExecutingAssembly()); //這樣既支持接口 又支持本身的類型 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsImplementedInterfaces().AsSelf(); //容器 var container = builder.Build(); //注入改成Autofac注入 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion #region 2.註冊MVC路由 var routes = RouteTable.Routes; routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); #endregion }
3.帶參數的控制器構造函數
public class HomeController : Controller { public HomeController(Say say) { } public string Index() { return "Hello World"; } } public class Say { public string Get() { return "Hello World"; } }
4.瀏覽器訪問~/
1.Install-Package Autofac.WebApi
2.因爲WebAPI須要,引用系統自帶Web.Http和Web.Http.WebHost
3.Application_Start添加此方法
protected void Application_Start(object sender, EventArgs e) { var configuration = GlobalConfiguration.Configuration; #region Autofac WebAPI注入 var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().AsSelf(); var container = builder.Build(); configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); #endregion #region 註冊Web API路由 configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); #endregion }
4.帶參數的控制器構造函數
public class ValuesController : ApiController { public ValuesController(Say say) { } public string Get() { return "Hello World"; } } public class Say { public string Get() { return "Hello World"; } }
5.瀏覽器訪問~/api/values
1.Install-Package Autofac.Wcf
2.Application_Start添加此方法
protected void Application_Start(object sender, EventArgs e) { #region WCF Autofac注入 var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().AsSelf(); var container = builder.Build(); //WCF IOC容器 AutofacHostFactory.Container = container; #endregion }
3.新建svc服務
public class TestService : ITestService { public TestService(Say say) { } public string DoWork() { return "Hello World"; } } public class Say { public string Get() { return "Hello World"; } } [ServiceContract] public interface ITestService { [OperationContract] string DoWork(); }
4.svc指令中加一句:
Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf"
5.wcftestclient
慚愧,很久沒發博客了