I have a single class called Foo:
using System;
using System.ComponentModel.Composition;
namespace MefTest
{
[Export]
internal class Foo
{
public Foo()
{
Console.WriteLine("created foo");
}
~Foo()
{
Console.WriteLine("Dead");
}
}
}
It's created as such:
using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MefTest
{
internal class Program
{
public static void Main()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
//EDIT: my problem, this returns Lazy<Foo> not Foo. Since I didn't call foo1.Value it was never actually created
var foo1 = container.GetExport<Foo>();
container.ReleaseExport(foo1);
foo1 = null;
GC.Collect();
Console.Read();
}
}
}
But it never seems to get disposed. I tried adding an IDisposible interface to it without any luck.
How can I ensure this gets cleaned up correctly? I thought that ReleaseExport would do it but the destructor never gets called, so it never appears to be cleaned up.
I've read http://mef.codeplex.com/wikipage?title=Parts%20Lifetime but I can't seem to see the problem with the above code.
The problem you have is that Foo is a shared export. If you want it disposed as is, you can implement IDisposable on it and then call Dispose on the container.
The other option is to mark Foo as non-shared which will result in ReleaseExport calling the Dispose method on it.
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
internal class Foo
{
public Foo()
{
Console.WriteLine("created foo");
}
~Foo()
{
Console.WriteLine("Dead");
}
}
The above is explained pretty well in the "Scoped operations and early reclaim of resources" section of the link you provided. Just remember that if you don't supply a PartCreationPolicy attribute, the export is shared by default.
Related
I have a project named A that has a class named ClassA.
ClassA has a method named ReadBlock() which creates a CloudBlockBlob object and calls one of its methods.
CloudBlockBlob is a class which is located in Microsoft.WindowsAzure.Storage.Blob namespace which is in Microsoft.WindowsAzure.Storage.dll.
My project A has a unit testing project named A.Tests.
Now, I want to test method ReadBlock(). To test it, I need to mock the CloudBlockBlob object and intercept the calls to its methods, return custom values and verify that the methods were called.
How can I mock an object that is fully created inside a method?
Can I somehow change project A's dll reference and reference it to a mock dll that creates a mock object instead the real one?
Can I override project A's call for classes inside the Microsoft.WindowsAzure.Storage.Blob with an implementation of my own in A.Tests class?
UPDATE:
The question is whether I can do this without modifying project A's code.
Thanks!
Without modifing class A code you won't be able to UT the ReadBlock method using Moq. You'll be able to UT this method using code weaving tools (MsFakes, Typemock Isolator, etc...)
For example(MsFakes):
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
ShimCloudBlockBlob.AllInstances.<the method you want to override> = (<the method arguments>) => {};
}
}
Inside the using scope you'll be able to override any method CloudBlockBlob has, through the property AllInstances.
In the next section I'm going to discuss all the other options you have...
Option 1:
public class A
{
private IBlockBlob _blockBlob;
public A(IBlockBlob blockBlob)
{
_blockBlob = blockBlob;
}
public void ReadBlock()
{
_blockBlob.DoSomething();
}
}
Since you create a new instance each time call ReadBlock(your method's current behavior) you better inject a factory instead of wrapper and DoSomething should be create; Option 2:
public class A
{
private readonly IFactoryBlockBlob _blobFctory;
public A(IFactoryBlockBlob blobFctory)
{
_blobFctory = blobFctory;
}
public void ReadBlock()
{
var blob = _blobFctory.Create();
}
}
However, based on your question and your comments it seems that your class 'has a dependency' instead of 'needs a dependency'.
(Mark Siemens wrote a great book about DI, this chart was taken from his book)
With this new piece of information your method should be something like; Option 3:
public class A
{
public void ReadBlock(ICloudBlob blob)
{
}
}
But you don't want to change the signature of the method:
public class A
{
public void ReadBlock()
{
ReadBlock(new CloudBlockBlob(<the params bla bla...>));
}
internal void ReadBlock(ICloudBlob blob)
{
}
}
Add InternalsVisibleToAttribute, then verify the behavior of the internal method.
By reading between the lines, it feels to me that your class is a kind of "legacy code" meaning that it can do the job, won't change, and verifying its behavior might be a waste of time. In the past I've posted a chart (in this answer) which may help you to decide the way to handle this case.
Its probably best to create a very simple mockable wrapper for CloudBlockBlob to improve your code's testability and inject it using dependency inversion.
Right now you probably have something like:
public class A
{
public void ReadBlock()
{
var blockBlob = new CloudBlockBlob();
blockBlob.DoSomething();
}
}
Instead, inject your wrapper into A so that the dependency on CloudBlockBlob is not known to A:
public class A
{
IBlockBlob _blockBlob
public A(IBlockBlob blockBlob)
{
_blockBlob = blockBlob;
}
public void ReadBlock()
{
_blockBlob.DoSomething();
}
}
Disclaimer, I work in Typemock.
You can do it without modifying project A's code using Isolator.
There is a simple example how it can be done:
public class Foo
{
public void ReadBlock()
{
var block = new CloudBlockBlob(new Uri("http://myUrl/%2E%2E/%2E%2E"));
var name = block.Name;
}
}
[TestMethod, Isolated]
public void TestReadBlock()
{
//Arrange
var fakeBlock = Isolate.Fake.AllInstances<CloudBlockBlob>();
Isolate.WhenCalled(() => fakeBlock.Name).WillReturn("Name");
//Act
var foo = new Foo();
foo.ReadBlock();
//Assert
Isolate.Verify.WasCalledWithAnyArguments(() => fakeBlock.Name);
}
Hope it helps!
Simple class using a TcpListener (this is just to present the problem, by no means this class makes any practical sence):
using System;
using System.Net.Sockets;
namespace NUnitTcp
{
public class Foo
{
TcpListener lst;
public Foo()
{
lst = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9090);
}
~Foo()
{
lst.Stop();
}
public void Start()
{
lst.Start();
}
public void Stop()
{
lst.Stop();
}
}
}
A simple application that uses Foo:
using System;
namespace NUnitTcp
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo();
f.Start();
}
}
}
This application runs fine, port is released as soon as the app ends and the app can be run again! Even without the destructor in Foo this would still happen!
A simple NUnit test with Foo:
using System;
using NUnitTcp;
using NUnit.Framework;
namespace NUnitTcpTests
{
[TestFixture]
public class TcpTests
{
[Test]
public void test1()
{
Foo f = new Foo();
f.Start();
Assert.True(true);
}
}
}
This test will run just once in the NUnit GUI thingy. Any subsequent execution of that test will throw an exception informing us that the port is in use. The NUnit GUI restart will release the port.
Would you consider this a bug? Seems to me like one...
CORRECTION - the test will randomly throw an exception, for me about 70% of the time.
The garbage collector is non-deterministic. It only closes promptly in the first example because the process exits. I strongly suggest you implement IDisposable instead of using a finalizer, then you can use:
using(Foo f = new Foo())
{
f.Start();
Assert.True(true);
}
safe in the knowledge that it will close promptly.
With something like:
public void Dispose()
{
if(lst != null) lst.Stop();
lst = null;
}
Port is in use until your Foo instance will not be collected by Garbage Collector. Also thus you have finalizer defined, it will require two garbage collection for finalizer to be called (Foo will be moved to finalization queue during first garbage collection, and finalizer will be possibly called during second garbage collection). If you want to be sure port will be released, I suggest you to close stop manually Foo in TearDown method:
private Foo _foo;
[SetUp]
public void Setup()
{
_foo = new Foo();;
}
[Test]
public void test1()
{
_foo.Start();
// Assert
}
[TearDown]
public void TearDown()
{
if (_foo != null)
_foo.Stop();
}
Also it would be nice to implement IDisposable on your Foo class, because it uses unmanaged resources, which should be released:
public class Foo : IDisposable
{
TcpListener lst;
public Foo()
{
lst = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9090);
}
public void Dispose()
{
lst.Stop();
}
}
Consider the following code sample that uses MEF to create an object of type Importer that imports an object of type ImporterExporter which in turn imports an object of type Exporter, i.e. Importer -> ImporterExporter -> Exporter. The catalog is managed by a CompositionUtility (obviously simplified for this example).
I know that MEF will resolve imports recursively on imported parts. However, because I want to have the option to instantiate each of these classes independetly, every class with imports also composes itself in its constructor to resolve those imports.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
namespace MefRecursionSample
{
class Program
{
static void Main(string[] args)
{
// var importerExporter = new ImporterExporter(); // include this and composition will work
var importer = new Importer();
Console.Write(importer.ImporterExporter.Exporter.Value); // should print 7
Console.ReadKey();
}
}
class CompositionUtility
{
static CompositionUtility()
{
var executingAssembly = Assembly.GetExecutingAssembly();
var assemblyCatalog = new AssemblyCatalog(executingAssembly);
_compositionContainer = new CompositionContainer(assemblyCatalog);
}
private static CompositionContainer _compositionContainer;
private static bool _isComposing;
public static void Compose(object part)
{
_compositionContainer.ComposeParts(part);
}
}
class Importer
{
public Importer()
{
CompositionUtility.Compose(this);
}
[Import]
public ImporterExporter ImporterExporter { get; set; }
}
[Export]
class ImporterExporter
{
public ImporterExporter()
{
CompositionUtility.Compose(this);
}
[Import]
public Exporter Exporter { get; set; }
}
[Export]
class Exporter
{
public int Value { get { return 7; } }
}
}
Running the code as is leads to a composition error "The ComposablePart of type MefRecursionSample.Importer' cannot be recomposed....", obviously because I am trying to explictly compose something that MEF also wants to compose.
What surprised me, was the fact that when I included the first line of the Main method, i.e. create an object of type ImporterExporter without MEF, this "double-composition" no longer caused an exception. Why is that?
Also, how could I make it work such that I could instantiate each of these indepennetly, yet also make them compose themselves when chained as in the sample. I figured I would introduce a boolean flag _compositionInProgress on the CompositionUtility and immediately return from Compose() when the flag is set to avoid the recursive composition. Is there a better way?
The flag I considered setting in the CompositionUtility's Compose method does not work, because there can be cases where the string of automatic imports is interrupted. For instance, in the question's example if Exporter instantiated a class in its constructor using new and this class would want to compose itself. Under the original solution, that class' call to Ccompose would return immediately, leaving the class uncomposed.
Because I want classes to compose themselves (thus making it unneccessary for their users to even know about MEF), the only solution was to establish the rule that classes with an [Export] attribute must not call Compose(this). Because they will be composed automatically by MEF when being imported, this would result in "double composition" and thus throw an exception.
If it is a requirement that classes marked with [Export] have to instantiated independently via new instead of nly imported via MEF, they have to have an addional constructor with a boolean flag which when set well trigger composition of that class. The default behavior, however, has to be no composition in order to avoid the aforementioned "double composition".
why not simply do this?
class Program
{
private static CompositionContainer _compositionContainer;
static void Main(string[] args)
{
//compose the container just one time in your app
var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
_compositionContainer = new CompositionContainer(assemblyCatalog);
var importer = _compositionContainer.GetExportedValue<Importer>();
Console.Write(importer.ImporterExporter.Exporter.Value); // should print 7
Console.ReadKey();
}
}
[Export]
class Importer
{
[ImportingConstructor]
public Importer(ImporterExporter imex)
{
this.ImporterExporter = imex;
}
public ImporterExporter ImporterExporter { get; private set; }
}
[Export]
class ImporterExporter
{
[ImportingConstructor]
public ImporterExporter(Exporter exporter)
{
this.Exporter = exporter;
}
public Exporter Exporter { get; private set; }
}
[Export]
class Exporter
{
public int Value { get { return 7; } }
}
What you really want to do (I think) is calling container.SatisfyImportsOnce() on an object and not ComposeParts .
ComposeParts adds all exports tree to the catalog while SatisfyImportsOnce each object is to itself , composing parts and thats it , no registeration of recursive exports , so you can call constructor or use importing constructor , you can have both.
James.
Basically, is there an easy way to dispose of the imports that are created by an ExportFactory<T>? The reason I ask is because the exports usually contain a reference to something that is still around, such as the EventAggregator. I don't want to run into the issue where I'm creating hundreds of these and leaving them laying around when they are not necessary.
I noticed that when I create the objects I get back a ExportLifetimeContext<T> which carries a Dispose with it. But, I don't want to pass back an ExportLifetimeContext to my ViewModels requesting copies of the ViewModel, hence I pass back the Value. (return Factory.Single(v => v.Metadata.Name.Equals(name)).CreateExport().Value;)
When you call Dispose on an ExportLifetimeContext<T> it will call dispose on any NonShared part involved in the creation of T. It won't dispose of any Shared components. This is a safe behaviour, because if the NonShared parts were instantiated purely to satisfy the imports for T, then they can safely be disposed as they won't be used by any other imports.
The only other way I think you could achieve it, would be to customise the Dispose method to chain the dispose call to any other member properties you import with, e.g.:
[Export(typeof(IFoo))]
public class Foo : IFoo, IDisposable
{
[Import]
public IBar Bar { get; set; }
public void Dispose()
{
var barDisposable = Bar as IDisposable;
if (barDisposable != null)
barDisposable.Dispose();
}
}
But as your type has no visibility of whether the imported instance of IBar is Shared or NonShared you run the risk of disposing of shared components.
I think hanging onto the instance of ExportedLifetimeContext<T> is the only safe way of achieving what you want.
Not sure if this helps, feels like unnecessary wrapping, but could you possibly:
public class ExportWrapper<T> : IDisposable
{
private readonly ExportLifetimeContext<T> context;
public ExportWrapper<T>(ExportLifetimeContext<T> context)
{
this.context = context;
}
public T Value
{
get { return context.Value; }
}
public void Dispose()
{
context.Dispose();
}
public static implicit operator T(ExportWrapper<T> wrapper)
{
return wrapper.Value;
}
public static implicit operator ExportWrapper<T>(ExportLifetimeContext<T> context)
{
return new ExportWrapper<T>(context);
}
}
Which you could possibly:
[Import(typeof(IBar))]
public ExportFactory<IBar> BarFactory { get; set; }
public void DoSomethingWithBar()
{
using (ExportWrapper<IBar> wrapper = BarFactory.CreateExport())
{
IBar value = wrapper;
// Do something with IBar;
// IBar and NonShared imports will be disposed of after this call finishes.
}
}
Feels a bit dirty...
I am trying to minimize entity framework connection context scope using "using" while at the mean time I want to be able to inject a context into my class.
I searched on internet but did not find a case like mine, or I am just doing something wrong, anyway, here is code:
[TestFixture]
public class Dummy
{
private IFoo ifoo;
[Test]
public void CreateIfNotExist()
{
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
Assert.IsNull(ifoo);//test fail here
}
[Test]
public void NotCreateIfExist()
{
ifoo = new Bar();
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
Assert.IsNull(ifoo);//test fail here
}
private IFoo GetNewIFoo()
{
if (ifoo == null)
{
ifoo = new Foo();//return new Foo();
}
return ifoo;
}
}
the first test failed, with a object sequence of foo created->foo do something->foo disposed(called by using on foo) while the state variable ifoo is still type of Foo().
Second test failed, with object life sequence as same as before.
I am confused as I thought GetNewIFoo() would return a reference of ifoo and using keyword would just call dispose on ifoo?
Also, is there any good way to control context scope while maintaining ability to inject IContext ?
Calling Dispose() does not clear the references (nor does it perform garbage collection). It simply calls the Dispose() method, which can (for example) close connections, files, etc - depending on the implementation. An object can be non-null and still disposed. Some objects allow you to see if an object is disposed; most don't.
Generally, if you are using something, you wouldn't write that variable somewhere else (i.e. you wouldn't write it as a field somewhere).
Meaning if using block is in next:
using (var foo = GetNewIFoo())
{
foo.Dosomething();
} // foo.Dipose() will be called automatically
which is the same as:
var foo = GetNewIFoo())
try
{
foo.Dosomething();
}
finally
{
foo.Dipose();
}
so foo is not null after using, but it's disposed.
Also:
using (var foo = GetNewIFoo())
{
foo.Dosomething();
}
//^ nothing below affects ifoo!!
Assert.IsNull(ifoo); // so why reference should be null??