Quantcast
Channel: Managed Extensibility Framework
Viewing all 265 articles
Browse latest View live

Created Unassigned: MEF2 error with custom metadata attributes [14625]

$
0
0
The nuget version of MEF (MEF2?) can't handle null values on custom metadata attributes when AllowMultiple is true. It will try to construct an array (which is ok) but TypeInspector.AddMetadata calls existingValue.GetType() -- if the metadata value is null this throws an exception.

An example is implementing a VS-style order attribute where you are supposed to set either the Before or After property but usually not both.

[MetadataAttribute]
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public sealed class OrderAttribute : Attribute
{
public string Before { get; set; }
public string After { get; set; }
}


New Post: Contract implementation is silently excluded from an ImportMany property collection

$
0
0
How can I programatically determine when a contract implementation is silently excluded from an ImportMany property collection due to an unfulfilled contract inside the implementation?

Consider a contract implementation that has an Import property contract which remains unfulfilled:
[Export(typeof(IAction))]
class Action2 : IAction
{
    [Import(typeof(INotImplemented))]
    public INotImplemented NotImplemented { get; set; }
    void IAction.Run() { Console.WriteLine("Action2 completed."); }
}
Due to the unfulfilled contract on the property, this implementation does not appear in any ImportMany collections:
[ImportMany]
public IEnumerable<IAction> Actions { get; set; }
This behavior is understandable, but presents a problem. The implementation is missing silently. There are no error messages from the composition engine.

I would like an exception to be thrown if any contracts are unfulfilled.

My question is:
How do I determine when an implementation of a contract is excluded from an ImportMany collection due to an unfulfilled Import property contract?

The following example shows the behavior I'm describing:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;

namespace DemoConsole
{
    class Program
    {
        //This contract is implemented by Action1 and Action2
        interface IAction
        {
            void Run();
        }

        //This contract has no implementation
        interface INotImplemented { }

        [Export(typeof(IAction))]
        class Action1 : IAction
        {
            void IAction.Run() { Console.WriteLine("Action1 completed."); }
        }

        [Export(typeof(IAction))]
        class Action2 : IAction
        {
            //This property contract remains unfulfilled
            [Import(typeof(INotImplemented))]
            public INotImplemented NotImplemented { get; set; }

            void IAction.Run() { Console.WriteLine("Action2 completed."); }
        }

        //This collection excludes Action2 due to an unfulfilled property contract
        [ImportMany]
        IEnumerable<IAction> Actions { get; set; }

        static void Main(string[] args)
        {
            var p = new Program();

            //My question is: How do I get the CompositionContainer to give a
            //warning when Action2 is excluded from the ImportMany Actions collection
            //property on the Program class?
            var catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(p);

            //Action2 is excluded from the ImportMany Actions collection
            //property on the Program class
            Console.WriteLine("Action count: {0}", p.Actions.Count());
            foreach (var action in p.Actions)
                action.Run();

            //Console output is:
            //Action count: 1
            //Action1 completed

            Console.ReadLine();
        }
    }
}

New Post: WCF service and MEF created instances lifetime

$
0
0
I have a WCF service class that is requested periodically from UI data it should retrieve.
In the service class I import usually shared parts (they are used by other WCF services and expensive to create)

On the WCF service class, in it's constructor we do on the application unique catalog we have Container.ComposeParts(instanceOftheWCFService)

The thing is, the service class instance constructor gets called periodically/makes calls to Container.ComposeParts periodically.

We are using MEF from .NET framework 4 and when I dump process memory I see all the instances of the WCF service class laying around, "leaking".

Qustion: When one does ComposeParts could MEF hold on to the instance created that imports shared parts. The class itself (WCF service) does not have any attributes from MEF, so MEF should not hold any references to it...

New Post: WCF service and MEF created instances lifetime

$
0
0
Just wanted to give more details. Looking for gc roots for one of the many service instances created I indeed confirm that a reference is being held to my service class:
!mroot 0000000006e9c660 
AppDomain 00000000006a4440: GCHandle(?) @ 000000001c0baf08
0000000006e9c728[System.ComponentModel.Composition.ReflectionModel.ReflectionComposablePart]
0000000006e9c660[Core.ConnectionService]

New Comment on "MetroChanges"

$
0
0
Hi, I'm really having a hard time finding a Windows Store App using these features coupled with Prism. Can you link me to a good example please? And a plus would be using ConventionBuilder. I would appreciate it very much. Thanks!...

New Post: MEF - what features can we expect?

$
0
0
Hi,

Where can I find a full working example version of Prism + MEF for Windows Runtime?

Thanks!...

New Post: UWP + Shared scope

$
0
0
Hi All,
I may be doing some stupid here as Shared do not seems to be working for me at all. Multiple instances created. Here it is:

Define interfaces:
namespace TestMef
{
    public interface IMainPageViewController
    {
        void DoWork();
    }
}

namespace TestMef
{
    public interface IRepoA
    {
        void DoWorkA();
    }
}

namespace TestMef
{
    public interface IRepoB
    {
        void DoWorkB();
    }
}

namespace TestMef
{
    public interface IWorker
    {
        void DoStuff();
    }
}
Create implementation
using System.Composition;
using System.Diagnostics;

namespace TestMef
{
    [Export(typeof(IRepoA)), Shared]
    public class RepoA : IRepoA
    {
        public RepoA()
        {
            Debug.WriteLine("Created RepoA");
        }

        public void DoWorkA()
        {
            Debug.WriteLine("DoWorkA");
        }
    }
}

using System.Composition;
using System.Diagnostics;

namespace TestMef
{
    [Export(typeof(IRepoB)), Shared]
    public class RepoB : IRepoB
    {
        public RepoB()
        {
            Debug.WriteLine("Created RepoB");
        }

        public void DoWorkB()
        {
            Debug.WriteLine("DoWorkB");
        }
    }
}

using System.Composition;
using System.Composition.Hosting;
using System.Diagnostics;
using System.Reflection;

namespace TestMef
{
    [Export(typeof(IWorker))]
    public class Worker : IWorker
    {
        [Import]
        public IRepoA RepoA { get; set; }

        [Import]
        public IRepoB RepoB { get; set; }

        public Worker()
        {
            Debug.WriteLine("Created Worker");
            var configuration = new ContainerConfiguration().WithAssembly(typeof(App).GetTypeInfo().Assembly);
            using (var container = configuration.CreateContainer())
            {
                container.SatisfyImports(this);
            }
        }

        public void DoStuff()
        {
            Debug.WriteLine("DoStuff");
        }
    }
}

using System.Composition;
using System.Composition.Hosting;
using System.Diagnostics;
using System.Reflection;

namespace TestMef
{
    [Export(typeof(IMainPageViewController))]
    public class MainPageViewController : IMainPageViewController
    {
        [Import]
        public IRepoA RepoA { get; set; }

        [Import]
        public IRepoB RepoB { get; set; }

        [Import]
        public IWorker IWorker { get; set; }

        public MainPageViewController()
        {
            Debug.WriteLine("Created MainPageViewController");
            var configuration = new ContainerConfiguration().WithAssembly(typeof(App).GetTypeInfo().Assembly);
            using (var container = configuration.CreateContainer())
            {
                container.SatisfyImports(this);
            }
        }

        public void DoWork()
        {
            Debug.WriteLine("DoWork");
        }
    }
}
Add this to main page class
using System.Composition;
using System.Composition.Hosting;
using System.Reflection;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;


namespace TestMef
{
    public sealed partial class MainPage : Page
    {
        [Import]
        public IMainPageViewController MainPageViewController { get; set; }

        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var configuration = new ContainerConfiguration().WithAssembly(typeof(App).GetTypeInfo().Assembly);
            using (var container = configuration.CreateContainer())
            {
                container.SatisfyImports(this);
            }
        }
    }
}
But the output not exactly what I expect

'TestMef.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'Anonymously Hosted DynamicMethods Assembly'.
Created MainPageViewController
Created RepoA
Created RepoB
Created Worker
Created RepoA
Created RepoB
Created RepoA
Created RepoB
Created Worker
Created RepoA
Created RepoB
The program '[9420] TestMef.exe' has exited with code 0 (0x0).


WTF is going on ?

Is there any good tutorial for this version of MEF for UWP.

I am using version 1.0.30

Many thanks.

New Post: UWP + Shared scope

$
0
0
Think I found why

This call in MainPageViewController and Worker not required.
var configuration = new ContainerConfiguration().WithAssembly(typeof(App).GetTypeInfo().Assembly);
            using (var container = configuration.CreateContainer())
            {
                container.SatisfyImports(this);
            }
I must say documentation is not entirely clear.

New Post: What is Up with This Project?

$
0
0
Hello,

I have spent the past hour trying to figure out MEF2. For starters, it appears that the current release has been available since the beginning of this year, but the documentation is terrible, to say the least. The only decent articles I can find on any site is this one:
http://blogs.microsoft.co.il/bnaya/2013/01/06/mef-20-toc/

And one on CodePlex. The samples and code that are used within these articles reference classes that simply do not exist. This is very concerning. Where are the documents and examples for MEF2? Is this project even still alive? It seriously has the look and feel of something that has yet again abandoned by MSFT. Trust me, I'm a former Silverlight developer. ;)

Thank you for any insight,
Michael

New Comment on "Documentation"

$
0
0
@exet: Say it in English, please!

Created Unassigned: MEF2 - troubles with exporting value types (bool, int, etc.) [14626]

$
0
0
Hi,

I'm trying export properties with types like boolean or integer, but I'm getting this exception:

Expression of type 'System.Boolean' cannot be used for return type 'System.Object'

I find out problem with building export expression in System.Composition.TypedParts.Discovery.DiscoveredPropertyExport. For now it looks like:

```
var activator = Expression.Lambda<CompositeActivator>(
Expression.Property(
Expression.Convert(Expression.Call(Expression.Constant(partActivator), s_activatorInvoke, args), _property.DeclaringType),
_property),
args);
```

but I guess it could be fixed by changing convert type

```
var activator = Expression.Lambda<CompositeActivator>(
Expression.Property(
Expression.Convert(Expression.Call(Expression.Constant(partActivator), s_activatorInvoke, args), _property.DeclaringType.IsValueType ? typeof(object) : _property.DeclaringType),
_property),
args);
```

However, I've no idea about impact of that change to other parts of MEF2. Could someone say something about how big deal is that change?

I attached simple project reproducing bug.

greetings

Created Unassigned: Missing source for Microsoft.Composition [14627]

$
0
0
I can't seem to find the source code for the Microsoft.Composition nuget package anywhere, but Roslyn needs it, and [the .NET Foundation site](https://www.dotnetfoundation.org/mef) seems to imply that it would be found here. So where is it?

Commented Unassigned: Missing source for Microsoft.Composition [14627]

$
0
0
I can't seem to find the source code for the Microsoft.Composition nuget package anywhere, but Roslyn needs it, and [the .NET Foundation site](https://www.dotnetfoundation.org/mef) seems to imply that it would be found here. So where is it?
Comments: Hello! _Microsoft.Composition_ now lives in https://github.com/dotnet/corefx Hope this helps Nick

New Post: What is Up with This Project?

$
0
0
LOL... I guess I got my answer. :P

New Post: What is Up with This Project?


New Post: How do you use this with Prism?

$
0
0
I can't seem to find a way to use this with Prism without having to use:
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
..to create my AggregateCatalog, my goal to mirror my Windows, Phone and Desktop app's using MEF2. So far I only can find examples using a Console app. Where can I find one using MEF2 in Windows, Phone or Desktop?

Thanks!...

Created Unassigned: MEF exceptions are pre-Disposed [14628]

$
0
0
Exceptions thrown by MEF throw ObjectDisposedException if the CompositionContainer has been disposed (as when the ```try``` is outside the ```using```. This is atypical: ```Exception```s aren't supposed to be ```IDisposable```.

Code:

```
using System;
using System.ComponentModel.Composition.Hosting;

namespace Segway.Service.Applications.MfgrMove.ListenerLogInterpreter
{
static class Program
{
#region Non-Public Class (Static) Constants and Variables
private static CompositionContainer _container;
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main ()
{
try
{
System.Windows.Forms.Application.EnableVisualStyles ();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault (false);

using (ApplicationCatalog catalog = new ApplicationCatalog ())
using (_container = new CompositionContainer (catalog))
{
try
{
using (IMainViewModel mainModel = GetInstance<IMainViewModel> ())
{
mainModel.StartModel ();
}
}
catch (Exception exc)
{
Console.WriteLine ("Inside the container and catalog");
DescribeException (exc);
throw;
}
}
}
catch (Exception exc)
{
Console.WriteLine ("Exception in Program:");
DescribeException (exc);
}
}

/// <summary>
/// Creates an instance of a type.
/// </summary>
/// <typeparam name="T">
/// The type (typically an interface) of the object to be created. By default, singletons
/// are created.
/// </typeparam>
/// <returns>
/// An instance of the type <typeparamref name="T"/>.
/// </returns>
public static T GetInstance<T> ()
{
return _container.GetExport<T> ().Value;
}

/// <summary>
/// Describes an exception and any inner exceptions to the Console.
/// </summary>
/// <param name="exc">
/// The exception to be described.
/// </param>
private static void DescribeException (Exception exc)
{
try
{
while (exc != null)
{
Console.WriteLine ("Exception: {0}", exc.GetType ().Name);
Console.WriteLine ("Message: {0}", exc.Message);
Console.WriteLine ("Stack Trace: {0}", exc.StackTrace);
exc = exc.InnerException;
if (exc != null)
{
Console.WriteLine ("Inner exception:");
}
}
}
catch (ObjectDisposedException e)
{
Console.WriteLine ("Accessing the exception raised an ObjectDisposedException.");
}
}
}
}
```

Results:

```
The thread 0x1b20 has exited with code 0 (0x0).
'Listener Log Interpreter.vshost.exe' (CLR v4.0.30319: Listener Log Interpreter.vshost.exe): Loaded 'C:\Users\brian.hetrick\Documents\Visual Studio 2015\Projects\Database Move\Listener Log Interpreter\bin\Debug\Listener Log Interpreter.exe'. Symbols loaded.
'Listener Log Interpreter.vshost.exe' (CLR v4.0.30319: Listener Log Interpreter.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'. Symbols loaded.
Exception thrown: 'System.ArgumentException' in Listener Log Interpreter.exe
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
Exception thrown: 'System.ComponentModel.Composition.Primitives.ComposablePartException' in System.ComponentModel.Composition.dll
Exception thrown: 'System.ComponentModel.Composition.CompositionException' in System.ComponentModel.Composition.dll
Exception thrown: 'System.ComponentModel.Composition.CompositionException' in System.ComponentModel.Composition.dll
Exception thrown: 'System.ComponentModel.Composition.CompositionException' in mscorlib.dll
Inside the container and catalog
Exception: CompositionException
Message: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

1) Value must be IMainView implementation
Parameter name: value

Resulting in: An exception occurred while trying to create an instance of type 'Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel'.

Resulting in: Cannot activate part 'Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel'.
Element: Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel --> Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel --> DirectoryCatalog (Path="C:\Users\brian.hetrick\Documents\Visual Studio 2015\Projects\Database Move\Listener Log Interpreter\bin\Debug\")

Resulting in: Cannot get export 'Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel (ContractName="Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.IMainViewModel")' from part 'Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel'.
Element: Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel (ContractName="Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.IMainViewModel") --> Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.MainViewModel --> DirectoryCatalog (Path="C:\Users\brian.hetrick\Documents\Visual Studio 2015\Projects\Database Move\Listener Log Interpreter\bin\Debug\")

Stack Trace: at System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart)
at System.ComponentModel.Composition.Primitives.Export.get_Value()
at System.ComponentModel.Composition.ExportServices.Exception thrown: 'System.ComponentModel.Composition.CompositionException' in Listener Log Interpreter.exe
Exception thrown: 'System.ObjectDisposedException' in System.ComponentModel.Composition.dll
The thread 0x199c has exited with code 0 (0x0).
The thread 0x22f8 has exited with code 0 (0x0).
The program '[5880] Listener Log Interpreter.vshost.exe' has exited with code 0 (0x0).
GetCastedExportedValue[T](Export export)
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.Program.GetInstance[T]() in C:\Users\brian.hetrick\Documents\Visual Studio 2015\Projects\Database Move\Listener Log Interpreter\Program.cs:line 60
at Segway.Service.Applications.MfgrMove.ListenerLogInterpreter.Program.Main() in C:\Users\brian.hetrick\Documents\Visual Studio 2015\Projects\Database Move\Listener Log Interpreter\Program.cs:line 28
Exception in Program:
Exception: CompositionException
Accessing the exception raised an ObjectDisposedException.
```

New Post: how to add user defined values to MEF object to access from Business and Data layer

$
0
0
is there an way to include user defined values ex:logged in user id to MEF object , so that we can access the value across the layer in different project.

let me know the steps if possible.

Reviewed: MEF Analysis Tool (mefx) for .NET 4.0 Beta (6月 17, 2016)

$
0
0
Rated 5 Stars (out of 5) - 非要回复才能下载

New Post: MEF thread safety

$
0
0
The export providers like:
  • CompositionContainer
  • ComposablePartExportProvider
  • CatalogExportProvider
have dedicated constructors that accept parameter (bool isThreadSafe) indicating that it should be "true if export provider must be thread-safe; otherwise, false.".

We know that even if we specify "true" - above classes won't be thread-safe for operations that causes recomposition (e.g. executing composition or exports change in the uderlying catalog).

Does it still means that if we provide synchronization for operations causing recompositon - other operations will be guaranteed to be thread safe? (assuming isThreadSafe=true)

Other words:
  • we set isThreadSafe=true
  • we put lock on operations causing recomposition (so that Compose(...), Catalogs.Add(...) are synchronized)
  • we do not synchronize GetExports operations or access to the exported objects via Lazy<> imports
Does it is still thread-safe?
Viewing all 265 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>