编程语言
首页 > 编程语言> > c# – 抽象工厂和控制反转在运行时解决

c# – 抽象工厂和控制反转在运行时解决

作者:互联网

我有以下类和接口结构,我很难尝试让代码完成我需要的工作.

public interface IUserManager
{
    int Add(User user);
}

public class UserManagerA : IUserManager{}
public class UserManagerB : IUserManager{}

在这个例子中,我使用Ninject作为IoC容器,但如果其他容器解决了这个问题,我可以更改它:

这是在我的NinjectWebCommon.cs中:

void RegisterServices(IKernel kernel)
{
    string userRole = CurrentUser.Role;//this gets the user logged in
    //This is the part I do not how to do
    //I wish I could just type this in:
    kernel.Bind<IUserManager>().To<UserManagerA>()
        .When(userRole == "RoleA"); // this doesn't work obviously
    kernel.Bind<IUserManager>().To<UserManagerB>()
        .When(userRole == "RoleB"); // same doesn't work
}

所有这一切,以便在我的(MVC)控制器中我可以这样做:

public class UserController
{
    private readonly IUserManager _userManager;
    public UserController(IUserManager userManager)
    {
        _userManager = userManager;
    }
    public ActionResult Add(User user)
    {
        //this would call the correct manager
        //based on the userRole
        _userManager.Add(user);
    }
}

我一直在阅读有关抽象工厂的文章,但没有找到解释如何将工厂与IoC容器集成并传递在运行时获得的参数来解决实现的文章.

解决方法:

如果IUserManager实现的数量不是很多(不太可能达到100个实现),您可以使用Strategy Pattern在合成期间解析所有UserManager实例,然后选择在运行时使用的最佳实例.

首先,我们需要一种将IUserManager实现映射到角色的方法.

public interface IUserManager
{
    int Add(User user);
    bool AppliesTo(string userRole);
}

public class UserManagerA : IUserManager
{
    // Add method omitted

    public bool AppliesTo(string userRole)
    {
        // Note that it is entirely possible to 
        // make this work with multiple roles and/or
        // multiple conditions.
        return (userRole == "RoleA");
    }
}

public class UserManagerB : IUserManager
{
    // Add method omitted

    public bool AppliesTo(string userRole)
    {
        return (userRole == "RoleB");
    }
}

然后我们需要一个策略类,它只是根据userRole选择正确的实例.组成应用程序时,DI容器提供IUserManager实例.

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))
        {
            // Note that you could optionally specify a default value
            // here instead of throwing an exception.
            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;//this gets the user logged in

        // Get the correct UserManger according to the role
        IUserManager userManager = this.userManagerStrategy.GetManger(userRole);

        // Do something with userManger
    }
}

void RegisterServices(IKernel kernel)
{
    kernel.Bind<IUserManager>().To<UserManagerA>();
    kernel.Bind<IUserManager>().To<UserManagerB>();

    // Ninject will automatically supply both IUserManager instances here
    kernel.Bind<IUserManagerStrategy>().To<UserManagerStrategy>();

    kernel.Bind<ISomeService>().To<SomeService>();
}

此方法不要求您将容器注入应用程序.没有使用服务地点.

另请注意,每次向应用程序添加新UserManager时都不需要修改switch case语句.何时使用UserManager的逻辑是UserManager实现的一部分,逻辑执行的顺序由DI配置决定.

此外,无论您使用哪个DI容器,这都可以使用.

你可以将它与RagtimeWilly的答案中的CurrentUserProvider结合起来,以便将用户角色转换为使用它的服务.

参考:Best way to use StructureMap to implement Strategy pattern

标签:c,dependency-injection,asp-net-mvc,ioc-container,abstract-factory
来源: https://codeday.me/bug/20190612/1223220.html