Last post Jul 23, 2019 04:10 PM by PatriceSc
Jul 19, 2019 07:44 AM|cenk1536|LINK
I am using basic authentication in my API. I use Unity as DI container. I wonder if this registration is enough for User Validation? Or should I add to RegisterType<UnitOfWork>(new HierarchicalLifetimeManager()) it?
public static class UnityConfig
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
var container = new UnityContainer();
/// Configured Unity Container.
public static IUnityContainer Container => container.Value;
public static void RegisterTypes(IUnityContainer container)
container.RegisterType<IGameServices, GameServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());
Here is User Validate:
public class UserValidate : IUserValidate
private readonly UnitOfWork _unitOfWork;
/// Public constructor.
public UserValidate(UnitOfWork unitOfWork)
_unitOfWork = unitOfWork;
/// Public method to authenticate user by user name and password.
/// <param name="userName"></param>
/// <param name="password"></param>
public async Task<bool> Login(string userName, string password)
var user = await _unitOfWork.UserRepository.Get(u => u.userName.Equals(userName, StringComparison.OrdinalIgnoreCase) && u.password == password);
if (user == null) return false;
Jul 19, 2019 07:13 PM|bruce (sqlwork.com)|LINK
can not tell without knowing the lifetime requirements of UnitOfWork. As a UnitOfWork is stored, then UserValidate must match the same lifetime.
My guess from your other thread is that you really do not understand the DI lifetime for request objects in asp.net. You should probably switch to DI factories that create one time instances, rather that trying to share single request only instances.
as asp.net 4.* is thread agile (can switch threads for the same request, or use the same thread for concurrent requests), it requires using a request context to pass request objects between pipeline events. Async processing in asp.net 4.* has logic to manage
the saving and restoring this context between async calls. Your DI container has to be tied to the request context somehow to create request scoped instances.
note: asp.net core is slightly different. multiple current requests are handled by the same thread, but a request can not switch threads. this still makes thread local storage useless, and requires the request context (HttpContext) to passed via the pipeline.
Jul 23, 2019 04:10 PM|PatriceSc|LINK
So to me it should be :
container.RegisterType<IGameServices, GameServices>().RegisterType<UnitOfWork>(new TransientLifetimeManager());
so that each controller get its own instance (which seems enough as far as I can see). Later you could change that to scope the DbContext to the http request if this is what you need instead.
Both Container and Hierachical are creating a singleton (ie create a new object the first time and then returns the same object on subsequent resolves which is a disaster for a DbContext)