相关疑难解决方法(0)

依赖注入统一 - 条件解析

有条件的解决是目前我​​还不了解的最后一件事.

让我们说我们有一个界面IAuthenticate:

public interface IAuthenticate{
    bool Login(string user, string pass);
}
Run Code Online (Sandbox Code Playgroud)

现在我有两种类型的身份验证.

Twitter认证

public class TwitterAuth : IAuthenticate
{
  bool Login(string user, string pass)
{
   //connect to twitter api
}

}
Run Code Online (Sandbox Code Playgroud)

Facebook Auth

public class FacebookAuth: IAuthenticate
{
  bool Login(string user, string pass)
{
   //connect to fb api
}

}
Run Code Online (Sandbox Code Playgroud)

在unity配置中注册类型:

unityContainer.RegisterType<IAuthenticate, TwitterAuth>();
unityContainer.RegisterType<IAuthenticate, FacebookAuth>();
Run Code Online (Sandbox Code Playgroud)

在我们的控制器中通过DI注入对象:

private readonly IAuthenticate _authenticate;

public AuthenticateController(IAuthenticate authenticate)
{
    _authenticate = authenticate;
}



// login with twitter
public virtual ActionResult Twitter(string user, string …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection inversion-of-control unity-container

14
推荐指数
2
解决办法
1万
查看次数

Unity Container多个相同接口的实现

我正在研究统一容器,并且有一个关于如何将类的构造解析为接口的多个不同实现的快速问题.

这是我的代码:

public interface IRenderer
{
    void DrawSquare(Square square);
    void DrawCircle(Circle circle);
}

public interface IShape
{
    void Draw(IRenderer renderer);
}

public class Dx11Renderer : IRenderer
{
    public void DrawSquare(Square square)
    {
    }

    public void DrawCircle(Circle circle)
    {
    }
}

public class GlRenderer : IRenderer
{
    public void DrawSquare(Square square)
    {
    }

    public void DrawCircle(Circle circle)
    {
    }
}

public class Circle : IShape
{
    public void Draw(IRenderer renderer) { renderer.DrawCircle(this); }   
}

public class Square
{
    public void Draw(IRenderer …
Run Code Online (Sandbox Code Playgroud)

.net c# unity-container

8
推荐指数
1
解决办法
1万
查看次数

依赖注入类型选择

最近,我遇到了一个必须基于参数选择类型的问题。例如:用于发送通知的类,该类应根据输入参数选择正确的通道(电子邮件,短信,...)。

我看起来像这样:

public class NotificationManager 
{
    IEmail _email;
    ISms _sms;

    public NotificationManager (IEmail email, ISMS sms) 
    {
        _email = email;
        _sms = sms;
    }

    public void Send(string type) 
    {
        switch(type) 
        {
            case "email":
                _email.send;
                break;

            case "sms":
                _sms.send;
                break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是,当我使用这种构造时,构造函数在发送通知的所有不同方法中迅速增长。

我真的不喜欢这样,这使得对选择单元进行单元测试变得难以操作。

我不能简单地说,new email();因为通知类型的电子邮件将依赖IEmailManager,这只会解决问题。

是否有某种模式可以执行相同的操作,但是方式更好,更清洁?

c# architecture dependency-injection

2
推荐指数
1
解决办法
373
查看次数