如何在Unity依赖注入中解析具体类

时间:2017-06-29 18:55:59

标签: c# dependency-injection unity-container

我似乎对如何使用DI容器实现策略模式感到困惑。

我有一个策略界面:

public interface IUserCompaniesInviteStrategy
    {
        bool InviteUserToCompany(UserCompaniesInviteRequest userCompaniesInviteRequest);
    }

以及几个具体的课程:

public class ConcreteExistingUserInviteStrategy : IUserCompaniesInviteStrategy

public class ConcreteNewUserInviteStrategy : IUserCompaniesInviteStrategy

如何将Unity与此连接?

    container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>();
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>();

显然不起作用......

我试过了:

container.RegisterType<IUserCompaniesInviteStrategy<ConcreteExistingUserInviteStrategy>, ConcreteExistingUserInviteStrategy>();
        container.RegisterType<IUserCompaniesInviteStrategy<ConcreteNewUserInviteStrategy>, ConcreteNewUserInviteStrategy>();

public interface IUserCompaniesInviteStrategy<T>

这似乎不起作用。

我认为我在这里要做的是使用命名类型,所以像:

container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>("1");
            container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>("2");

但是,我有构造函数注入设置并使用container.resolve对我来说不是一个很好的选择,因为n层架构和链接依赖关系我必须解决。

如何将命名类型注入构造函数?有没有更好的方法去做我想做的事情? (创建一个解析为两个具体策略的界面)

更新

我看了With Unity how do I inject a named dependency into a constructor?。接受的答案不会起作用,因为我不会在我的域中依赖Unity,也不需要它。我尝试了StrategyResolver,但我得到了:

  An error occurred when trying to create a controller of type 'UserController'. Make sure that the controller has a parameterless public constructor.

这表明存在DI问题。

StrategyResolver和IStrategyResolver与示例中的相同:

public class StrategyResolver : IStrategyResolver
    {
        private IUnityContainer container;

        public StrategyResolver(IUnityContainer unityContainer)
        {
            this.container = unityContainer;
        }

        public T Resolve<T>(string namedStrategy)
        {
            return this.container.Resolve<T>(namedStrategy);
        }
    }

public interface IStrategyResolver
    {
        T Resolve<T>(string namedStrategy);
    }

我的配置:

container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>("ExistingUser");
            container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>("NewUser");
            container.RegisterType<IStrategyResolver, StrategyResolver>();
            container.RegisterType<IUserFactory, UserFactory>();

混凝土:

public class ConcreteExistingUserInviteStrategy : IUserCompaniesInviteStrategy
public class ConcreteNewUserInviteStrategy : IUserCompaniesInviteStrategy

然后我称之为:

_strategyResolver.Resolve<IUserCompaniesInviteStrategy>("ExistingUser");

不确定它有什么问题。

0 个答案:

没有答案