简体   繁体   English

统一容器寄存器类型的内部类?

[英]Can unity container register type of internal class?

I have create the project and put the Interface and class in the same folder. 我创建了项目并将Interface和类放在同一个文件夹中。 I'm using Unity container to resolve the interface for object of the class. 我正在使用Unity容器来解析类对象的接口。 Now I have another assembly that want to access the assembly about. 现在我有另一个想要访问程序集的程序集。 I don't want anyone to access my class directly. 我不希望任何人直接访问我的班级。 So if it is possible to register type of the internal class it will good for me. 因此,如果可以注册内部类的类型,这对我有好处。 Any idea? 任何想法?

You could try around with Friend assemblies , but I think it will just cause you problems in the long run. 可以尝试使用Friend程序集 ,但我认为从长远来看它只会给您带来问题。

Instead I would consider two other options. 相反,我会考虑另外两个选择。

Option A : Use a factory. 选项A :使用工厂。

Suggested here: Unity 1.2 Dependency injection of internal types . 建议这里: Unity 1.2依赖注入内部类型

public class FactoryClass
{
   public IMyInterface CreateInstance()
   {
       return new MyInternalClass(); 
   }
}

internal class MyInternalClass : IMyInterface
{
}

Also consider using an public class with an internal constructor, which would force an internal class to create the instance. 还要考虑使用带有内部构造函数的公共类,这会强制内部类创建实例。 More information here: What's the difference between a public constructor in an internal class and an internal constructor? 更多信息: 内部类中的公共构造函数与内部构造函数之间的区别是什么? .

public class MyAlmostInternalClass // in lack of better name
{
    internal MyAlmostInternalClass() {}
}

Option B : Reconsider your class completely 选项B :完全重新考虑你的课程

Why does it need to be internal? 为什么需要内部? Shouldn't the other assembly use the interface anyway? 其他组件不应该使用接口吗? Make it sealed if you don't want anyone the derive from it and don't have any public properties other than the one from the interface it implements. 如果您不希望任何人从中派生出来并且除了它实现的接口之外没有任何公共属性,请将其密封 Then there's really no reason to use the class over the interface. 然后,没有理由在界面上使用该类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM