Autofac 的構造函數注入方式


介紹

該篇文章通過一個簡單的 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 IUserRepository:IRepository<UserInfo>
{

}
public class UserRepository : IUserRepository
{
    private static List<UserInfo> _users;

    public UserRepository()
    {
        _users = new List<UserInfo>();
    }

    public void Add( UserInfo item )
    {
        _users.Add( item );
    }

    public List<UserInfo> Find( Expression<Func<UserInfo, bool>> predicate = null )
    {
        if ( predicate == null ) return _users;

        return _users.Where( predicate.Compile() ).ToList();
    }

    public void Modifty( UserInfo item )
    {
        var user = _users.Find( u => u.Id == item.Id );

        if ( user == null ) return;

        user.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 IUserAppService:IAppService<UserInfo>
{

}
public class UserAppService : IUserAppService
{
    private readonly IUserRepository _userRepository;

    public UserAppService(IUserRepository userRepository)
    {
        this._userRepository = userRepository;
    }

    public void Add( UserInfo item )
    {
        this._userRepository.Add( item );
    }

    public List<UserInfo> Find( Expression<Func<UserInfo, bool>> predicate = null )
    {
        return this._userRepository.Find( predicate );
    }

    public void Modify( UserInfo item )
    {
        this._userRepository.Modifty( item );
    }
}
public class HomeController : Controller
{
    private IUserAppService _userAppService;

    public HomeController(IUserAppService userAppService)
    {
        this._userAppService = userAppService;
    }

    public ActionResult Index()
    {
        ViewBag.Message = "Home-Index";
        this._userAppService.Add( new UserInfo { Id = 1, Name = "JRoger" } );
        ViewBag.Users = this._userAppService.Find();

        return View("~/Views/Home/Index.cshtml");
    }
}

構造函數注入代碼

雖然以上代碼沒有注釋,但覺得結構已經非常清楚了,不用再過多的解釋。 但有一點需要注意一下,在 HomeController 類和 UserAppService 類的構造函數中都有傳進來的實例對象(我已經用橘紅色標記了)。這也是使用構造函數注入的其中一個關鍵點。
下面來看一下實現依賴注入的核心代碼怎么調用:

private void _InitIoC()
{
    var builder = new ContainerBuilder();

    builder.RegisterControllers( typeof( MvcApplication ).Assembly );

    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();

    var container = builder.Build();
    var resolver = new AutofacDependencyResolver( container );

    DependencyResolver.SetResolver( resolver );
}

其它:

Autofac.dll 版本 3.4.0.0
Autofac.Integration.Mvc.dll 版本 3.3.4.215 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM