I have created a project to understand windsor castle and singleton. To achieve this I have the following code
Controller:
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);
}
}
Singleton Base Class:
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
}
Service Class:
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
}
}
So in the controller instead of passing OfflineUserService.instance; I want to pass IOfflineUserService.instance so that I can use it. I don't know how to achieve this. Dependency injection is working fine if I pass it through constructor
public AdminController(IOfflineUserService offlineUser)
{
_offlineUser = offlineUser;
}
but as I want to use singleton so to achieve this I can create the instance as mention in the code but I don't know how to create the singleton instance of an interface. Please suggest if I am doing anything wrong as I am trying to understand the behavior so that I can start using it in Projects.