我開始研究一個新項目,我來自一個直接和'天真'編程。Autofac依賴注入實現
現在我正在關注使用IoC容器,特別是使用Autofac的依賴注入模式。
比方說,我有一個簡單的會話工廠:
namespace Warehouse.Data
{
public class SessionFactory
{
private static ISessionFactory _sessionFactory;
private static ISystemSetting _systemSetting;
SessionFactory(ISystemSetting systemSetting)
{
_systemSetting = systemSetting;
InitializeSessionFactory();
}
private static void InitializeSessionFactory()
{
_sessionFactory = Fluently.Configure()
.Database(DatabaseConfiguration)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyMap>())
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return _sessionFactory.OpenSession();
}
}
}
而在Bootstrap.cs,我配置autofac這樣的:
namespace Warehouse.Infrastructure
{
using Autofac;
public class Bootstrap
{
public IContainer Configure()
{
var builder = new ContainerBuilder();
builder.RegisterType<SystemSetting>().As<ISystemSetting>();
builder.RegisterType<UserRepository>().As<IUserRepository>();
return builder.Build();
}
}
}
我的問題是這樣的:
- 我如何使用Autofac將SessionFactory依賴項解析爲ISystemSetting? 每當我想使用SessionFactory時,是否需要使用
builder.Resolve<ISystemSetting>
作爲參數? - 依賴注入模式,或者也許只是Autofac,帶有很多新的單詞,如Service,Resolve,Singleton等。我從哪裏可以從頭開始學習這些東西?每個其他DI框架都一樣嗎?
- 我需要了解IoC容器如何在具有多層的項目中工作,每層都需要對Autofac的引用嗎?
謝謝。
什麼我不明白你的榜樣,是SessionFactory的,因爲它也包含了「靜態ISessionFactory _sessionFactory;」。所以你在會話工廠中封裝一個sessionfactory?在我看來,你想舉辦一個會議課。 – Egi 2013-05-08 12:24:09