MEF的依赖注入 [英] Dependency Injection with MEF

查看:111
本文介绍了MEF的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习依赖注入。



我做了一个测试应用程序试用它。输出应该是测试附加字符串,但它一直给我一个NullReferenceException。任何帮助?

I am trying to learn dependency injection.

Ive made a test app to try it out. The output should be "Testing Appended string", but it keeps giving me a NullReferenceException. Any help?

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.ComponentModel.Composition;

namespace buildtest
{
    interface IAppend
    {
        string Append(string str);
    }

    [Export(typeof(IAppend))]
    class Appender : IAppend
    {

        public string Append(string str)
        {
            return str + "Appended string";
        }
    }

    class AppHelper
    {
        [Import(typeof(IAppend))]
        public IAppend App { get; set; }

    }

    class runner
    {
        public void Run()
        {
            AppHelper t = new AppHelper();
            //Composition
            CompositionContainer container;
            try
            {
                var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
                container = new CompositionContainer(catalog);
                container.ComposeParts(this);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            t.App.Append("Testing ");

            Console.ReadLine();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            new runner().Run();
        }
    }
}

推荐答案

container.ComposeParts(this);



使用此行,您可以尝试将可组合部分放入这个 !!!


With this line you try to put the composable parts into this!!!

container.ComposeParts(t);



And现在你把它放进你的新AppHelper !!!



[由SA建议更多解释为什么有效]

MEF是一个插件可以从不同程序集加载类的引擎,从加载的程序集中的类创建实例,并将该对象分配给托管程序集中的某些属性。

这些对是根据导出/导入属性生成的。

例如在我们的代码中,我们有一个使用Export [IAppend]签名的外部(几乎)类,我们有一个类--AppHelper - 具有使用Import [IAppend]签名的属性。

当通过ComposeParts调用MEF引擎时,引擎会查找这样的对并建立连接。如果我们传递一些没有匹配符号属性的对象(如此),MEF引擎将返回而不进行任何操作。但是,如果我们将一个对象(如t)传递给引擎,它会将外部类的实例分配给匹配的属性 - 在我们的例子中是App。


And now you put it into your new AppHelper!!!

[As advised by SA more explanation why that works]
MEF is a plugin engine that can load classes from different assemblies, create instances from the classes in the loaded assembly and assign that object to some property in the hosting assembly.
The pairs are made according the Export/Import attributes.
For instance in our code we have an external (almost) class signed with Export[IAppend] and we have a class - AppHelper - that has property signed with Import[IAppend].
When calling the MEF engine via ComposeParts, the engine looks for such pairs and make the connection. If we pass some object that has no properties with the matching sign (like this) MEF engine will return without any action. However if we pass an object - like t - to the engine it will assign an instance of the external class to the matching property - in our case App.


你没有显示异常的位置抛出对象引用未设置为对象实例的消息。



不用担心。这是检测和修复的最简单的案例之一。它只是意味着某些引用类型的某个成员/变量通过使用和它的实例(非静态)成员解除引用,这要求此成员/变量为非null,但实际上它似乎为null。只需在调试器下执行它,它将停止抛出异常的执行。在该行上设置一个断点,重新启动应用程序并再次到达这一点。评估下一行中涉及的所有引用,并查看哪一个为null,而不需要为null。解决这个问题之后,修复代码:要么确保将成员/变量正确初始化为非空引用,要么将其检查为null,如果为null,则执行其他操作。



另请参阅:想要在按钮点击时显示下一条记录。但是如果下一条记录功能的条件对象引用没有设置为对象的实例 [ ^ ]。



有时候,你不能在调试器下,由于一个或另一个原因做到这一点。一个非常讨厌的情况是,只有在调试信息不​​可用时构建软件时才会出现问题。在这种情况下,你必须使用更难的方式。首先,你需要确保你永远不会通过静默处理异常来阻止异常的传播(这是开发人员对自己的犯罪,但很常见)。您需要在每个线程的最顶层堆栈帧上捕获绝对所有异常。如果处理类型 System.Exception 的异常,则可以执行此操作。在处理程序中,您需要记录所有异常信息,尤其是 System.Exception.StackTrace

http://msdn.microsoft.com/en-us/library/system.exception.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.exception。 stacktrace.aspx [ ^ ]。



堆栈跟踪只是一个字符串,显示从throw语句到处理程序的异常传播的完整路径。通过阅读,您总能找到目的。对于日志记录,使用类 System.Diagnostics.EventLog

http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx [ ^ ]。







OP澄清后(谢谢你,stubobis1!):



眼前的问题现在显而易见了。在您指出的行中, t.App 为空。在同一行中,您尝试通过调用 Append(string)取消引用 t.App (这是属性getter调用)的计算结果上的空值,这会导致您抱怨的异常。



现在,为什么 t.App 为空?因为你从来没有给它赋值。解决方案1解释了你可以做什么。



祝你好运,

-SA
You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].



After OP's clarification (thank you, stubobis1!):

The immediate problem is now obvious. In the line you pointed out, t.App is null. In the same line, you try to dereference the result of calculation of t.App (which is the property getter call) by calling Append(string) on the null value, which result in the exception you complained about.

Now, why t.App is null? Because you never assigned it a value. Solution 1 explains what you could have done.

Good luck,
—SA


这篇关于MEF的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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