IUserManager ( 100 ), UserManager , .
-, IUserManager .
public interface IUserManager
{
int Add(User user);
bool AppliesTo(string userRole);
}
public class UserManagerA : IUserManager
{
public bool AppliesTo(string userRole)
{
return (userRole == "RoleA");
}
}
public class UserManagerB : IUserManager
{
public bool AppliesTo(string userRole)
{
return (userRole == "RoleB");
}
}
, userRole. IUserManager DI, .
public interface IUserManagerStrategy
{
IUserManager GetManager(string userRole);
}
public class UserManagerStrategy
: IUserManagerStrategy
{
private readonly IUserManager[] userManagers;
public UserManagerStrategy(IUserManager[] userManagers)
{
if (userManagers == null)
throw new ArgumentNullException("userManagers");
this.userManagers = userManagers;
}
public IUserManager GetManager(string userRole)
{
var manager = this.userManagers.FirstOrDefault(x => x.AppliesTo(userRole));
if (manager == null && !string.IsNullOrEmpty(userRole))
{
throw new Exception(string.Format("User Manager for {0} not found", userRole));
}
return manager;
}
}
public class SomeService : ISomeService
{
private readonly IUserManagerStrategy userManagerStrategy;
public SomeService(IUserManagerStrategy userManagerStrategy)
{
if (userManagerStrategy == null)
throw new ArgumentNullException("userManagerStrategy");
this.userManagerStrategy = userManagerStrategy;
}
public void DoSomething()
{
string userRole = CurrentUser.Role;
IUserManager userManager = this.userManagerStrategy.GetManger(userRole);
}
}
void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserManager>().To<UserManagerA>();
kernel.Bind<IUserManager>().To<UserManagerB>();
kernel.Bind<IUserManagerStrategy>().To<UserManagerStrategy>();
kernel.Bind<ISomeService>().To<SomeService>();
}
, . .
, case switch, , UserManager. UserManager UserManager , , DI.
, , DI .
CurrentUserProvider RagtimeWilly , .
: StructureMap