I have an object hierarchy similar to the following:
interface IVideoStream { }
abstract class VideoStream : IVideoStream { }
interface IVideoStreamTypeA : IVideoStream { /* Specific for type A */ }
interface IVideoStreamTypeB : IVideoStream { /* Specific for type B */ }
class VideoStreamTypeA : IVideoStreamTypeA { }
class VideoStreamTypeB : IVideoStreamTypeB { }
There should be a single instance of both VideoStreamTypeA and VideoStreamTypeB, as they wrap some resources. Some classes consume IVideoStreamTypeA or IVideoStreamTypeB directly, and some classes take a list of IVideoStream.
The register code looks like this:
class MyRegistry: Registry
{
public MyRegistry()
{
For<IVideoStreamTypeA>().Use<VideoStreamTypeA>()
.Ctor<>() // Specific initialization
For<IVideoStreamTypeB>().Use<VideoStreamTypeB>()
.Ctor<>() // Specific initialization
For<IVideoStreamTypeA>().Singleton();
For<IVideoStreamTypeB>().Singleton();
}
}
Finally, there are some classes that take a list of IVideoStream:
class MyClass
{
public MyClass(IEnumerable<IVideoStream> streams) { }
}
With the current registry code, the "streams" parameter is empty. How do I get StructureMap to inject the two instances from above?
My current approach is to use the following:
Forward<IVideoStreamTypeA, IVideoStream>();
Forward<IVideoStreamTypeB, IVideoStream>();
But I'm not sure it's the best solution
Related
We have many XUnit tests in our project that we use to test our API (each with many InlineData). The problem is that we can access a subset of the API via two other connection methods.
Today we use a CollectionDefinition to keep the connection to the main API (it is time consuming to create the connection) and we intend to have three separate CollectionDefinition, one for each connection path.
I imagine I will create a new attribute I can add to each test class to tell which connection methods it should use. And then it uses the CollectionDefinitions that are connected to the various connections.
I am considering using [assembly: Xunit.TestFramework ("name", "assembly")] and implementing my own XunitTestFramework. But I can not figure out how to achieve what I want. Do you have any suggestions on how I should proceed?
You can accomplish this as follows:
Make an abstract class that defines the methods common to all your API's, and derive specific classes from it which create the specific connection. Make a CollectionDefinition and a fixture for each type of connection:
using Xunit;
namespace SO71300821_multipleCollectionDefinition
{
public abstract class APIConnectionMethod
{
public bool isOK { get; } = true;
};
public class APIConnectionMethod0 : APIConnectionMethod
{
public APIConnectionMethod0()
{
// ... initialize API connection ...
}
}
[CollectionDefinition("Collection0")]
public class Collection0 : ICollectionFixture<APIConnectionMethod0>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
public class APIConnectionMethod1 : APIConnectionMethod
{
public APIConnectionMethod1()
{
// ... initialize API connection ...
}
}
[CollectionDefinition("Collection1")]
public class Collection1 : ICollectionFixture<APIConnectionMethod1>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
public class APIConnectionMethod2 : APIConnectionMethod
{
public APIConnectionMethod2()
{
// ... initialize API connection ...
}
}
[CollectionDefinition("Collection2")]
public class Collection2 : ICollectionFixture<APIConnectionMethod2>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
}
Make an abstract base test class that implements all the tests that need to work for each of the various API's:
using Xunit;
namespace SO71300821_multipleCollectionDefinition
{
public abstract class UnitTestBase
{
APIConnectionMethod connection;
public UnitTestBase(APIConnectionMethod connection_)
{
connection = connection_;
}
[Fact]
public void connectionIsOK()
{
Assert.NotNull(connection);
Assert.True(connection.isOK);
}
}
}
Derive a public class from the base test class for each type of connection:
using Xunit;
namespace SO71300821_multipleCollectionDefinition
{
[Collection("Collection0")]
public class UnitTestSpecific0 : UnitTestBase
{
public UnitTestSpecific0(APIConnectionMethod0 connection_) : base(connection_)
{
}
}
[Collection("Collection1")]
public class UnitTestSpecific1 : UnitTestBase
{
public UnitTestSpecific1(APIConnectionMethod1 connection_) : base(connection_)
{
}
}
[Collection("Collection2")]
public class UnitTestSpecific2 : UnitTestBase
{
public UnitTestSpecific2(APIConnectionMethod2 connection_) : base(connection_)
{
}
}
}
If there are tests that only work for certain specific types of connections, you can implement them in these classes.
The test discoverer will find the tests in UnitTestBase in each of the derived classes and run them in those classes, so you'll have a separate test in the Test Explorer for each of the derived classes.
The information from https://xunit.net/docs/shared-context helped me prepare this answer and some of the code is copied from there.
I am building some integration tests for my database stored procedures.
I have setup an xUnit project and implemented Fixture pattern. To show you:
public class MyTableTest : IClassFixture<DatabaseFixture>
{
public MyTableTest()
{
//DO SOMETHING
}
[Fact]
public void Test()
{
//DO SOMETHING
}
}
And:
public class DatabaseFixture : IDisposable
{
public void Dispose()
{
// ... clean up test data from the database ...
}
}
This DatabaseFixture is something that will be shared among all of my test classes. Why? Because I want some common logic happening at the end of every test, such as cleanup.
Point is that I need to know which table to clean, which in my example would be MyTable. Such information I would retrieve by using reflection when the Dispose method will run against the instance of MyTableTest being disposed . How can I achieve this? Is it even possible (and correct) trying to achieve this? Thanks in advance.
You can have a TableName property in the DatabaseFixture class. Then receive an instance of the class in constructor of your test classes and set that TableName property. Later you can use it in dispose to do some cleanup.
public class MyTableTest : IClassFixture<DatabaseFixture>
{
DatabaseFixture databaseFixture;
public MyTableTest(DatabaseFixture databaseFixture)
{
this.databaseFixture = databaseFixture;
databaseFixture.TableName = "MyTable";
}
[Fact]
public void Test()
{
}
}
public class DatabaseFixture : IDisposable
{
//...
public string TableName { get; set; }
//...
public void Dispose()
{
// Cleanup based on TableName
}
}
To learn more about sharing context in xUnit, take a look at:
Shared Context between Tests
Comparing xUnit.net to other frameworks
You can use custom attributes to attach any arbitrary data to your derived Fixture class.
For example
you can create a TableNameAttribute like this:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class TableNameAttribute : Attribute
{
public string Name { get; }
public TableNameAttribute(string name)
{
this.Name = name;
}
}
you can apply this attribute to your derived fixture class:
[TableName("MyTable")]
public class MyTableFixture : DatabaseFixture { }
you can use that fixture class inside your test
public class MyTableTest : IClassFixture<MyTableFixture>
{
[Fact]
public void Test()
{
//DO SOMETHING
}
}
Finally this is how you can retrieve the Name from the Dispose method:
public abstract class DatabaseFixture : IDisposable
{
...
public void Dispose()
{
var attribute = this.GetType().GetCustomAttribute(typeof(TableNameAttribute));
if (attribute is TableNameAttribute tableNameAttr)
Console.WriteLine(tableNameAttr.Name);
}
}
Is it even possible (and correct) trying to achieve this?
No. Reflection cannot tell type T in what context T is used; reflection only sees T's declaration.
More specific to your situation, reflection cannot tell type DatabaseFixture that it is being used as a type parameter of generic interface IClassFixture in the declaration of MyTableTest. In other words, for this set of declarations,
class A { }
class B <T> { }
class C : B<A> { }
A cannot reflectively determine that it is used in C's declaration, but C can know about its usage of A:
typeof(C)
.BaseType // B
.GetGenericArguments()[0] // A
How can I achieve this?
Depending on how you are using DatabaseFixture, you could get the calling test class using the StackTrace (if you are really bent on using reflection). Here is a simple example:
public class DisposableObject : System.IDisposable
{
public void Dispose()
{
var stack = new System.Diagnostics.StackTrace();
// This will log the name of the class that instantiated and disposed this.
System.Console.WriteLine(stack.GetFrame(1).GetMethod().DeclaringType.Name);
return;
}
}
If your DatabaseFixture is not called directly from your test class, you will either have to know the offset to pass to GetFrame(int), or you will need to search each frame until you find the first DeclaringType that matches your requirements (e.g., BaseType is IClassFixture with Generic Argument DatabaseFixture), something like this:
System.Type testClassType = new StackTrace()
.GetFrames()
.Where(f =>
{
System.Type baseType = f.GetMethod().DeclaringType.BaseType;
return typeof(IClassFixture<DatabaseFixture>).IsAssignableFrom(baseType);
})
.FirstOrDefault() // First matching result (assuming you found any)
?.GetMethod() // Get the reflected Method
.DeclaringType; // Get the type (e.g. class) that declares this method.
string tableName = testClassType.Name.Replace("Test", "");
Otherwise, you will need to set the table name manually, as suggested by Reza and Peter.
I have the requirement to be able to perform many conversions of external models to my own internal models.
I have decided to apply the Adapter pattern, but I want to make it as generic as possible. So effectively, I want it to be handle both "single" POCO's, but if i need to pass/adapt a collection then this also must work eg:
IEnumerable<IAdaptee> OR IList<TAdaptee>
and return my own adapted object(s):
IEnumerable<IAdapted> OR IList<TAdapted>
I want to do something like the following:
public interface IGenericAdapter
{
TAdapted Adapt<TAdapted,TAdaptee>(TAdaptee adaptee);
}
Where I am coming unstuck is when I build my "Adapter" class, and then implement the above interface, I am getting constraint mismatch errors. This of course, makes sense, because If i am applying constraints to the classes which implement the interface, and the interface doesn't have them, then of course errors occur.
So:
public class AToBAdapter
{
public TAdapted Adapt<TAdapted,TAdaptee>(TAdaptee adaptee)
where TAdapted: IList<FooAdapted>
where TAdaptee: IList<FooAdaptee>
{
// I want my constraints to be active here, as I need to perform specific operations here
}
}
The above works fine in and of itself, which is fine. But I want to hide all this behind a generic interface that I can use whenever it suits.
Of course, Once i add this it fails due to no constraints on the interface, yet constraints on the implementing class.
public class AToBAdapter:IAdapterGeneric
What's the magic bullet here which will enable me to build a truly generic Adapter - I'm guessing certain constraints on the interface? casting? but need assistance on the best course of action.
Thanks,
Chud
If you have access to your external models, you could use an interface as a marker:
public interface IAdaptee { }
public interface IAdapted { }
And use those interfaces as your adapter interface constraints:
public interface IGenericAdapter<out TAdapted, in TAdaptee>
where TAdaptee : IAdaptee
where TAdapted : IAdapted
{
TAdapted Adapt(TAdaptee adaptee);
}
You could pass this adapter into a helper method for adapting multiple objects (assuming the adapt logic stays the same for multiple):
public IEnumerable<TAdapted> AdaptMultiple<TAdapted, TAdaptee>
(IEnumerable<TAdaptee> adaptees, IGenericAdapter<TAdapted, TAdaptee> adapter)
where TAdaptee : IAdaptee
where TAdapted : IAdapted
{
return adaptees.Select(adapter.Adapt);
}
For example, we can construct the following concrete classes:
public class ConcreteAdaptee : IAdaptee { }
public class ConcreteAdapted : IAdapted { }
public class ConcreteAdapter : IGenericAdapter<ConcreteAdapted, ConcreteAdaptee>
{
public ConcreteAdapted Adapt(ConcreteAdaptee adaptee)
{
// Adapt Logic
return new ConcreteAdapted();
}
}
And adapt them as such:
IGenericAdapter<ConcreteAdapted, ConcreteAdaptee> adapter = new ConcreteAdapter();
var adaptee = new ConcreteAdaptee();
var adapted = adapter.Adapt(adaptee);
var adaptees = new List<ConcreteAdaptee>();
var adapteds = AdaptMultiple(adaptees, adapter);
consider the following example :
interface IDog
{
void Bark();
}
interface ICat
{
void Meow();
}
class SomeDog : IDog
{
public void Bark()
{
Console.WriteLine(#"bark bark");
}
}
class SomeCat : ICat
{
public void Meow()
{
Console.WriteLine(#"meow meow");
}
}
class CatToDogAdapter : IDog
{
private ICat cat;
public CatToDogAdapter(ICat cat)
{
this.cat = cat;
}
public void Bark()
{
cat.Meow();
}
}
new Dog().Bark(); // bark bark
new CatToDogAdapter().Bark();// meow meow
this is how adapter works.
Let say you have a model MyAdaptedData and you recive data containing HotelName, Name,PropertyName from agoda , booking and tripadviser
for each booking model you need to write adapter
AgodaAdapter : MyAdaptedData{
public AgodaAdapter(AgodaModel agodaModel){
....
}
public stirng HotelName{
get{
return agodaModel.HotelNamebyAgoda;
}
}
....
}
Same for booking and tripadvisor.
Adapter pattern helps you to retrieve necessary data from external models.
Then you need to create specific adapter depending on the adaptee type. Use Factory method pattern
MyAdaptedData AdaptersFactory(object adaptee){
if(adaptee is AgodaModel)
return new AgodaAdapter(adaptee);
....
if(adaptee is XBookingModel)
return new XBookingAdapter(adaptee);
}
Hi I have a a MEF container which detects metadata attributes and I would like to expand on this and allow classes to implement additional intefaces (in the example below, where i want to implement an additional interface IPluginSettings).
The module GUID identifier is critical as it is reconciled with a module ID in my database application, if I query the MEF container for my imported interfaces I can loop through them:
foreach (Lazy<T,IPluginMetadata> moduleInAssembly in m_Container.GetExports<T, IPluginMetadata>();)
{
T value = moduleInAssembly.Value; // instantiate an object of type T to test for implementations of other interfaces...
if (value is IPluginSettings)
{
// this module also contains an interface for settings!
}
Guid moduleInAssemblyId = Guid.Parse(moduleInAssembly.Metadata.PluginID);
}
I have some questions:
1) In the above scenario, I have to instantiate the class to test if I it implements a specific interface, is there a better way of doing this with Metadata and enhance the PluginExportAttribute to accept a list of secondary interface types?
2) How can I tell MEF container to import types that only have the PluginExportAttribute?
3) Or instead of having each plugin interface flexilbe/free to declare its own interface, would i be better off for plugins to implement a well-known plugin interface which contained a factory to instantiate the specific plugin interface? (Example of what i am asking is at the bottom of the code - last section)
4) Thanks to one proposed answer i am using code structured as per question 4 snipit below and it works! Out of curiosity, is there anyway to merge multiple seperate Export attributes into the PluginExportAttribute, perhaps in a constructor parameter to take a list of additional types to register?
Thanks,
Chris
public interface IPluginMetadata
{
string PluginID { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginExportAttribute : ExportAttribute, IPluginMetadata
{
public PluginExportAttribute(Type t, string guid)
: base(t)
{
PluginID = guid.ToUpper();
}
public string PluginID { get; set; }
}
[PluginExport(typeof(IAccountsPlugin),"BE112EA1-1AA1-4B92-934A-9EA8B90D622C")]
public class BillingModule : IAccountsPlugin, IPluginSettings
{
// my class contents
}
or would i be better of doing something like this...?
// or would i be better of by implementing a plugin base, and getting instances of the plugin via a secondary factory?
public interface IWellKnownPluginBase
{
Guid PluginID { get; }
Version Version { get; }
IPluginSettings Settings { get; }
Type GetPluginInterfaceType { get; }
object PluginInterfaceFactory();
}
public interface IMyPlugin
{
void DoSomethingCool();
}
[Export(typeof(IWellKnownPluginBase))]
public class MyPluginWrapper : IWellKnownPluginBase
{
private readonly string ID = "BE112EA1-1AA1-4B92-934A-9EA8B90D622C";
Guid PluginID { get { return Guid.Parse(ID); } }
Version Version { get {return new Version(1,0,0); } }
IPluginSettings Settings { get { return new SomethingThatImplementsIPluginSettings(); }
Type GetPluginInterfaceType { get { return gettype(IMyPlugin); }
object PluginInterfaceFactory() { return new MyPlugin(); }
class MyPlugin : IMyPlugin
{
void DoSomethingCool() {}
}
}
Question 4 - can PluginExport be rewritten to register multiple interfaces with a list of interfaces in the constructor?
[Export(typeof(IPluginSettings))]
[PluginExport(typeof(IAccountsPlugin),"BE112EA1-1AA1-4B92-934A-9EA8B90D622C")]
public MyModule class : IModule, IPluginSettings
{
}
In the above scenario, I have to instantiate the class to test if I it implements a specific interface, is there a better way of doing this with Metadata and enhance the PluginExportAttribute to accept a list of secondary interface types?
Normally you would do this by having multiple exports:
[Export(typeof(IPluginSettings))]
[Export(typeof(IModule))]
public class MyModule : IModule, IPluginSettings
{
}
Instead of checking whether an interface is present, the consumer (i.e. the importer, or in your case the caller of GetExports) can then just ask for the correct interface.
So, I'd like to hear what you all think about this.
I have a project where three different inheritance paths need to all implement another base class. This would be multiple inheritance and isn't allowed in C#. I am curious how I can implement this without code duplication.
EDIT: I don't own the three classes. The three classes are from 3rd party code. So I cannot make them all extend my base class.
Right now I am using three different classes, each one extending a different base class. Then I have the same code in each of the three abstract classes.
I could use a single interface, but I would still need to duplicate the code.
I could make some kind of static class that implements the code and then reference that in each of the 3 abstract classes. It would eliminate the duplication, but, I am not sure how I feel about this. I could implement Extensions methods on the interface, but then the interface itself would be empty and the extension methods (containing the duplicate code) would be in a totally different file, which seems not quite right. Plus I can't implement properties in extension methods...
How can I factor out the code duplication here?
EDIT, inheritance tree:
class Class1 : 3rdPartyBaseClass1 { }
class Class2 : 3rdPartyBaseClass2 { }
class Class3 : 3rdPartyBaseClass3 { }
I have code I want to be in each of the above Classes, but I cannot add it to the 3rdPartyClasses.
Create an interface that Class1, Class2, and Class3 can implement. Then put your code in extension methods so it will apply to all.
interface IMyInterface {
void Foo(); //these are the methods that these
//classes actually have in common
void Bar();
}
public class Class1 : 3rdPartyBaseClass1, IMyInterface {
// whatever
}
public static class IMyInterfaceExtensions {
public static void CommonMethod(this IMyInterface obj) {
obj.Foo();
obj.Bar();
}
}
public static class Program {
public static void Main() {
var instance = new Class1();
instance.CommonMethod();
}
}
OK, you can do something similar to my previous suggestion, and also similar to recursive's suggestion. For the functionality you require in all three of your derived classes, you can create a single Interface along with a single class (call it "Implementer" for kicks) that implements that Interface (and that has the actual code you want executed with each call).
In each of your derived classes, then, you implement the Interface and create a private instance of Implementer. In each of the interface methods, you just pass the call along to the private instance of Implementer. Because Implementer and your derived classes all implement your Interface, any changes you make to the Interface will require you to modify Implementer and the derived classes accordingly.
And all your code is in one place, except for all the lines passings the calls on to the private instance of Implementer (obviously multiple inheritance would be better than this, but you go to war with the army you have, not the army you wish you had).
Update: what about just adding a public instance of your class to each of the derived classes?
public class DerivedClass1 : ThirdPartyClass1
{
public MyClass myClass = new MyClass();
}
Or if you care who Demeter is and you get paid by LOC:
public class DerivedClass1 : ThirdPartyClass1
{
private MyClass _myClass = new MyClass();
public MyClass myClass
{
get
{
return _myClass;
}
}
}
Then you'd just call the MyClass methods like this:
DerivedClass1 dc1 = new DerivedClass1();
dc1.myClass.DoSomething();
This way, we could all go to sleep.
Similar to MusiGenesis's suggestion, if you need the functionality of the 3rd party classes but do not have to descend from them, you could use composition as follows:
class ThirdPartyBaseClass1
{
public void DoOne() {}
}
class ThirdPartyBaseClass2
{
public void DoTwo() { }
}
class ThirdPartyBaseClass3
{
public void DoThree() { }
}
abstract class Base
{
public void DoAll() { }
}
class Class1 : Base
{
public void DoOne() { _doer.DoOne(); }
private readonly ThirdPartyBaseClass1 _doer = new ThirdPartyBaseClass1();
}
class Class2 : Base
{
public void DoTwo() { _doer.DoTwo(); }
private readonly ThirdPartyBaseClass2 _doer = new ThirdPartyBaseClass2();
}
class Class3 : Base
{
public void DoThree() { _doer.DoThree(); }
private readonly ThirdPartyBaseClass3 _doer = new ThirdPartyBaseClass3();
}
This also gives you the freedom to define whatever interfaces you want and implement them on your classes.
Sounds like you need to insert the new abstract class into the inheritance tree at whatever point those three paths come together, but there really isn't enough information to tell. If you could post some of your inheritance tree, that would help a lot.
I think you may want to use composition instead of inheritance. Exactly how to do this depends on what the third party classes look like, and what your own code looks like. Some more specific code relating to your problem would be helpful, but for example, suppose you want to have three different third party GUI widgets that all need to be customized with your own initializer code.
Case 1: Suppose your third party widgets look like:
public interface IThirdPartyWidget {
public void doWidgetStuff();
}
public class ThirdPartyWidget1: ThirdyPartyWidget implements IThirdPartyWidget {
...
}
public class ThirdPartyWidget2: ThirdPartyWidget implements IThirdPartyWidget {
...
}
You can do:
public class MyWidget implements IThirdPartyWidget {
private IThirdPartyWidget delegateWidget;
public MyWidget(IThirdPartyWidget delegateWidget) {
this.delegateWidget = delegateWidget;
}
public void doWidgetStuff() {
delegateWidget.doWidgetStuff();
}
}
Case 2: Suppose you absolutely need to extend those widgets, and you have to refactor your own code:
public class MyWidget1: ThirdPartyWidget1 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
public class MyWidget2: ThirdPartyWidget2 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
This can become:
public class MyCodeRunner {
public void runMyCode() {
//...
}
}
public class MyWidget1: ThirdPartyWidget1 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
public class MyWidget2: ThirdPartyWidget2 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
Hope this makes sense!