私は、DryIocを使用してuserviewmodelで現在のユーザーのインスタンスを登録して取得します。これはCurrentUserConfigクラスですDRYIOCを使用してクラスを登録し、返されたモデルのインスタンスを取得
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;
}
}
これは私がDryIocを使用して達成したいものです。
var currentUserConfig = new CurrentUserConfig(container);
container.UseInstance(currentUserConfig);
container.RegisterDelegate<UserViewModel>(resolver =>
{
var objCurrentUserConfig = resolver.Resolve<CurrentUserConfig>();
return currentUserConfig.GetCurrentUser();
}, Reuse.InCurrentScope);
また、あなたがタイプして、ユーザーの設定を登録することがあります。:ユーザー設定のためのを登録することはないことを、
container.Register<CurrentUserConfig>(Reuse.Singleton);
container.RegisterDelegate<UserViewModel>(resolver =>
{
var objCurrentUserConfig = resolver.Resolve<CurrentUserConfig>();
return currentUserConfig.GetCurrentUser();
}, Reuse.InCurrentScope);
注これはSimpleInjector
var currentUserConfig = new CurrentUserConfig(container);
container.RegisterSingleton(currentUserConfig);
container.Register<UserViewModel>(() =>
{
var objCurrentUserConfig = container.GetInstance<CurrentUserConfig>();
return currentUserConfig.GetCurrentUser();
}, Lifestyle.Scoped);
は、なぜあなたは= _container.Resolve()' VARリポジトリを解決するのですか?スコープUserViewModelでシングルトンCurrentUserConfig で: - 『パラメータとしてIUserRepositoryシングルトンUserRepositoryで再帰 <『userRepository』 として –
dadhi
私はCurrentUserConfigにIUserRepositoryを注入した場合、私はエラー「パラメータとして UserViewModelを解決するときに再帰的な依存関係が検出され、』ユーザーを取得スコープ付きのUserController内のパラメータ "currentUser" < - recursive "したがって、なぜ私はCurrentUserConfigクラスにIUserRepositoryを注入しないのですか? –
CurrentUserConfig @dadhiで解決することの短所は何ですか? –