I want to register and get instance of current user in userviewmodel using DryIoc.Please how do i achieve this. This is the CurrentUserConfig class
public class CurrentUserConfig
{
private IContainer _container;
private UserViewModel _userViewModel;
public CurrentUserConfig(IContainer container)
{
_container = container;
_userViewModel = new UserViewModel();
}
public UserViewModel GetCurrentUser()
{
if (!string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name) && Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
if (_userViewModel == null || _userViewModel.UserId < 1)
{
try
{
var repository = _container.Resolve<IUserRepository>();
_userViewModel = Task.Run(async () => await repository.GetUserByUsername(Thread.CurrentPrincipal.Identity.Name)).Result;
}
catch (System.Exception ex)
{
//return exception error;
}
}
}
return _userViewModel;
}
}
This is what i want to achieve using DryIoc. This was done using SimpleInjector
var currentUserConfig = new CurrentUserConfig(container);
container.RegisterSingleton(currentUserConfig);
container.Register<UserViewModel>(() =>
{
var objCurrentUserConfig = container.GetInstance<CurrentUserConfig>();
return currentUserConfig.GetCurrentUser();
}, Lifestyle.Scoped);
Direct translation would be:
Alternatively you may register user config by type:
Note, that registering
IContainer
for user config is not required. DryIoc will automatically inject correctly scoped container instance.There may be a further improvement to register user with DryIoc
Made.Of
construct.Made.Of
enables registering with any instance or static class member returning the service. It is generally better thanRegisterDelegate
because DryIoc may analyse the service creation, and warn you about captive or recursive dependencies.