如何使用统一用内部类? [英] How can I use Unity with internal classes?

查看:79
本文介绍了如何使用统一用内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API应用,并正在使用Unity的依赖注入。该应用程序使用包含接口IDoStuff和实现接口的类的库:

I have a Web API application and am using Unity for dependency injection. The application uses a library containing an Interface IDoStuff and a class that implements the interface:

internal interface IDoStuff
{
    void DoSomething();
}

internal class DoStuff : IDoStuff
{
    public void DoSomething()
    {
        // Do some stuff
    }
}

该库还具有需要做的东西的公共类:

The library also has an public class that needs to do stuff:

public class NeedToDoStuff
{
    private IDoStuff doStuff;

    public NeedToDoStuff()
    {
        this.doStuff = new DoStuff();
    }

    internal NeedToDoStuff(IDoStuff doStuff)
    {
        this.doStuff = doStuff;
    }

    void ILikeToDoStuff()
    {
        doStuff.DoSomething();
    }
}

我想使用统一创造我的控制器NeedToDoStuff实例,也负责内部创建DoStuff类,而不是构造函数直接调用新的。不过,我可以看到这样做的唯一方法是使这两个IDoStuff接口和DoStuff类公共似乎我错了。这似乎是错误的,因为这些都是实现细节,只有库本身有关。我得到了与控制反转你允许顶层应用程序通过某种配置,使有关其底层实现的选择,但应该这是否意味着不再有需要的内部等?

I'd like to use Unity to create a NeedToDoStuff instance in my controller and to also be responsible for creating the DoStuff class internally, rather than the constructor calling new directly. However, the only way I can see to do this is to make both the IDoStuff interface and DoStuff class public which seems wrong to me. It seems wrong as these are implementation details and only relevant within the library itself. I get that with inversion of control you're allowing the top level application to make choices about its underlying implementations via configuration of some sort but should this mean that there's no longer a need for internal etc?

推荐答案

我已为我自己的答案,因为我相信它已经近乎回答我原来的问题。它可能不会像干净的设计选择,因为史蒂芬的建议,但爱它还是恨它,它允许为图书馆的内部类与团结一起使用。

I've posted my own answer as I believe it comes closest to answering my original question. It may not be as clean a design choice as Steven's recommendations but love it or hate it, it does allow for the internal classes of a library to be used in conjunction with Unity.

我需要做三次更新的类/接口:

I needed to make three updates to the classes/interfaces:


  1. 请接口公开。

  2. 请建设者公众。

  3. 介绍静态类/方法是从应用程序执行的主要统一注册逻辑称为库中进行统一登记启动。

这篇关于如何使用统一用内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆