介绍
该篇文章通过一个简单的 ASP.NET MVC 项目进行介绍如何使用 autofac 及 autofac 的 MVC 模块进行依赖注入。注入方式通过构造函数。在编写 aufofac 的依赖注入代码之前先准备一些基础类。
基础类
public class UserInfo
{
public int Id { get; set; } public string Name { get; set; }
}
public interface IRepository<T>
{
void Add( T item ); void Modifty( T item ); List<T> Find( Expression<Func<T, bool>> predicate = null );
}
public interface IProductRepository:IRepository<ProductInfo>
{ }
public class ProductRepository : IProductRepository
{
private static List<ProductInfo> _products = new List<ProductInfo>(); public void Add( ProductInfo item )
{
_products.Add( item );
} public List<ProductInfo> Find( Expression<Func<ProductInfo, bool>> predicate = null )
{
if ( predicate == null ) return _products; return _products.Where( predicate.Compile() ).ToList();
} public void Modifty( ProductInfo item )
{
var product = _products.Find( u => u.Id == item.Id ); if ( product == null ) return; product.Name = item.Name;
}
}
public interface IAppService<T>
{
void Add( T item ); void Modify( T item ); List<T> Find( Expression<Func<T, bool>> predicate = null );
}
public interface IProductAppService:IAppService<ProductInfo>
{ }
public class ProductAppService : IProductAppService
{
public IProductRepository ProductRepository { get; set; } public void Add( ProductInfo item )
{
this.ProductRepository.Add( item );
} public List<ProductInfo> Find( Expression<Func<ProductInfo, bool>> predicate = null )
{
return this.ProductRepository.Find( predicate );
} public void Modify( ProductInfo item )
{
this.ProductRepository.Modifty( item );
}
}
public class ProductController : Controller
{
public IProductAppService ProductService { get; set; } public ActionResult Index()
{
this.ProductService.Add( new ProductInfo { Id = , Name = "Lumia" } ); return View("~/Views/Product/Index.cshtml");
}
}
属性注入代码
以下代码中 PropertiesAutowired() 方法就是实现了属性注入的核心,从单词字面意思就可以看出其用意。
private void _InitIoC()
{
var builder = new ContainerBuilder(); builder.RegisterControllers( typeof( MvcApplication ).Assembly )
.PropertiesAutowired();
builder.RegisterAssemblyTypes( typeof( MvcApplication ).Assembly )
.Where( t => (t.Name.EndsWith( "Repository" ) || t.Name.EndsWith("AppService")) && !t.IsAbstract )
//.InstancePerDependency() //每次都创建一个对象
//.SingleInstance() //每次都是同一个对象
//.InstancePerLifetimeScope() //同一个生命周期生成的对象是同一个
.InstancePerRequest() //单个 Web / HTTP / API 请求的范围内的组件的共享一个实例。仅可用于支持每个请求的依赖关系的整合(如MVC,Web API,Web Forms等)。
.AsImplementedInterfaces()
.PropertiesAutowired(); var container = builder.Build();
var resolver = new AutofacDependencyResolver( container, new StubLifetimeScopeProvider( container ) ); DependencyResolver.SetResolver( resolver );
}
其它
Autofac.dll 版本 3.4.0.0
Autofac.Integration.Mvc.dll 版本 3.3.4.215