我創建了一個項目來了解Windsor城堡和單身人士。要做到這一點,我有以下代碼使用具有依賴注入的單例(Castle Windsor)
控制器:
public class AdminController : Controller
{
private readonly IOfflineUserService _offlineUser;
public AdminController()
{
_offlineUser = OfflineUserService.instance;
}
[OutputCache(Duration = 20, VaryByParam = "none", Location = OutputCacheLocation.Server, NoStore = true, SqlDependency = "Default:Admin")]
public ActionResult test()
{
var data = _offlineUser.GetAllOfflineUsers();
return View(data);
}
}
辛格爾頓的基類:
public abstract class SingletonBase<T> where T : class
{
#region Members
/// <summary>
/// Static instance. Needs to use lambda expression
/// to construct an instance (since constructor is private).
/// </summary>
private static readonly Lazy<T> sInstance = new Lazy<T>(() => CreateInstanceOfT());
#endregion
#region Properties
/// <summary>
/// Gets the instance of this singleton.
/// </summary>
public static T Instance { get { return sInstance.Value; } }
#endregion
#region Methods
/// <summary>
/// Creates an instance of T via reflection since T's constructor is expected to be private.
/// </summary>
/// <returns></returns>
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
#endregion
}
服務類:
public class OfflineUserService : SingletonBase<OfflineUserService>,IOfflineUserService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IUserRepository _userRepository;
private readonly IAdminRepository _adminRepository;
public OfflineUserService()
{
}
public OfflineUserService(IUnitOfWork unitOfWork,
IUserRepository userRepository,
IAdminRepository adminRepository,
)
{
_adminRepository = adminRepository;
_unitOfWork = unitOfWork;
_userRepository = userRepository;
}
public List<OfflineUsers> GetAllOfflineUsers()
{
//Some Code
}
}
所以在控制器強似OfflineUserService .instance;我想通過IOfflineUserService.instance以便我可以使用它。我不知道如何做到這一點。如果我通過它通過構造函數依賴注入工作正常
public AdminController(IOfflineUserService offlineUser)
{
_offlineUser = offlineUser;
}
但我想用單所以要實現這一點,我可以創建實例作爲代碼提及,但我不知道如何創建單一個接口的實例。請建議如果我做錯了什麼,因爲我正在試圖瞭解這種行爲,以便我可以開始在項目中使用它。
Thanx很多!!!!但我已經註冊的UnitOfWork爲Component.For() .ImplementedBy () .LifeStyle.PerWebRequest,所以它仍然會被視爲單????? –
是的,它會......實例是單例實例(OfflineUserService)的依賴。仔細閱讀關於俘虜依賴的ploeh文章...作爲解決方法,您應該有一個工廠(TypedFactory請參閱windsor維基)作爲您的單例(OfflineUserService)的依賴關係:工廠將根據組件註冊 – Crixo
創建實例Thanx很多!我會重新考慮我的設計模式。 –