【发布时间】:2018-01-31 06:43:04
【问题描述】:
我有一个非常简单的设置。
namespace ObjectNamespace
{
public class CustomProcessor : ICustomProcessor<myObject>
{
public CustomProcessorResult Execute(myObject Data)
{
try
{
var container = new UnityContainer();
// UnityConfigurationSection section = new UnityConfigurationSection();
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
// this gives Microsoft.Practices.Unity.Configuration.UnityConfigurationSection
section.Containers.Default.Configure(container);
var configuration = Container.Resolve<ICustomProcessorConfiguration>();
var emailer = container.Resolve<IEmailManager>();
var reportGenerator = container.Resolve<IReportGenerator>();
}
catch (Exception e)
{
Trace.WriteLine("It failed while trying to initialize the DI componenets");
throw;
}
错误消息是空引用异常。它显示在
section.Containers.Default.Configure(Container);
我的部分将返回我在 web.config 文件中的值,该文件在该行 (Microsoft.Practices.Unity.Configuration.UnityConfigurationSection) 上进行了注释
我只是为了实现这个 Execute 方法而束手无策。我不知道为什么它给我一个空引用错误。 Container 应该由 UnityConfigurationSection 配置。
这是我在 <configSections> 标签内的 web.config 文件
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, myCustom.dll" />
据我所知,这是解析和绑定到接口的方法。我做错了吗?
有没有其他的方法来设置一个部分?或配置容器?在解决之前?
编辑:在下面提供的一个答案之后,我尝试跳过代码的 section 部分,但 DI 组件仍未如它所说的那样被初始化"header comments" are missing 这是它在配置文件中查看的内容。这就是应用程序的设置方式。所以我猜想从配置"unity" section 中获取值是必不可少的。有什么办法可以将部分部分合并到我的代码中?让它配置我的容器?
我已经在myApp.cfg 文件中为 DI 映射了我的<unity> 标签(例如:用于电子邮件)
<type type= "myProject.Interfaces.IEmailManager, mySolution (dll name)"
mapTo="myProject.EmailManager, mySolution (dll name)" >
<lifetime type="singleton"/>
</type>
所以在另一个建议之后,我删除了所有基于 XML 统一的集成代码,我从 Unity 获得了ResolutionFailedException。我已经删除了所有 xml 集成并按照建议进行了注册,但现在我得到了 build operation failed, Required attribute , 'header comment' not found。我什至在myApp.cfg 中设置了一个别名作为ControlledLifetimeManager 的typeAlias,我也把它去掉了。没有统一参考,这是我得到的错误。它试图从 web.config 第 43 行读取并给我这个错误。没有任何需要或我知道的标题注释注册。
【问题讨论】:
-
您可能希望将配置文件中的相关内容(即“unity”部分)添加到问题中。
-
Type部分的部分看起来错误 - 我怀疑UnityConfigurationSection是在您的“myCustom.dll”中定义的...... -
@AlexeiLevenkov myCustom.dll 包含许多其他 dll。我已经得到了与它一起工作的机会。该部分按预期返回。至少作为一个字符串!
-
@thestralFeather7 合并程序集和基于反射的代码很难做到正确。恐怕你需要发布太多信息才能在 SO 上回答这个问题......
标签: c# asp.net dependency-injection unity-container