MEF Add module twice to catalog - module

Do you know how to add the same module twice to a catalog with different parameters?
ITest acc1 = new smalltest("a", 0)
ITest acc2 = new smalltest("b", 1)
AggregateCatalog.Catalogs.Add(??)
AggregateCatalog.Catalogs.Add(??)
Thanks in advance!

As MEF is limited to its usage of attributes and can be configured by using the Import and Export attributes unlike the flexibility usually provided by IoC Containers, just how one may extend a Part in MEF, one may extend it from a referenced DLL, you could also do something similar where a class inherits from a previous MEF Part by creating a class which exposes some properties with the [ExportAttribute]. The attribute is not limited to the usage on a class, but can be applied to properties. For example, how about something like this.
public class PartsToExport
{
[Export(typeof(ITest))]
public Implementation A
{
get { return new Implementation("A", 5); }
}
[Export(typeof(ITest))]
public Implementation B
{
get { return new Implementation("B", 10); }
}
}
public interface ITest
{
void WhoAmI(Action<string, int> action);
}
[Export]
public class Implementation : ITest
{
private string _method;
private readonly int _value;
public Implementation(string method, int value)
{
_method = method;
_value = value;
}
public void WhoAmI(Action<string, int> action)
{
action(_method, _value);
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
var tests = container.GetExportedValues<ITest>();
foreach (var test in tests)
{
test.WhoAmI((s, i) => Console.WriteLine("I am {0} with a value of {1}.", s, i));
}
}
}
This outputs the following to the console:
I am A with a value of 5.
I am B with a value of 10.

Related

How to write Xunit test case of factory design pattern code block which is tightly coupled?

I would like to write xunit test case of below method. Could you please suggest alternate design so i can write xunit test case with minimum change in my current project.
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = ContextFactory.Current.GetDomain<EmployeeDomain>().GetEmployeeFilterAsync(id,
CurrentUser.CompanyId, filter); // Not able write unit test case , please suggest alternate design.
return View("View", response);
}
}
current design is as follow
public interface IDomain
{
}
public interface IContext
{
D GetDomain<D>() where D : IDomain;
string ConnectionString { get; }
}
public class ApplicationContext : IContext
{
public D GetDomain<D>() where D : IDomain
{
return (D)Activator.CreateInstance(typeof(D));
}
public string ConnectionString
{
get
{
return "DatabaseConnection";
}
}
}
public class ContextFactory
{
private static IContext _context;
public static IContext Current
{
get
{
return _context;
}
}
public static void Register(IContext context)
{
_context = context;
}
}
//var response = ContextFactory.Current.GetDomain**< EmployeeDomain>**().GetEmployeeFilterAsync(id,
CompanyId, filter);
This line serve purpose to call specific class method i.e GetEmployeeFilterAsync from EmployeeDomain. Although it is very handy and widely used in our application but due to design issue i am not able to write unit
test case.
Could you please suggest design so with the minimum change we can write unit test case.
Don't use the Service Locator anti-pattern, use Constructor Injection instead. I can't tell what AssetDomain is from the OP, but it seems as though it's the dependency that matters. Inject it into the class:
public class ProbablySomeController
{
public ProbablySomeController(AssetDomain assetDomain)
{
AssetDomain = assetDomain;
}
public AssetDomain AssetDomain { get; }
public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
{
using (var tracer = new Tracer("AssetController", "Index"))
{
RemoveReturnUrl();
ViewBag.JobId = id;
var response = AssetDomain.GetAssetFilterAsync(id, CurrentUser.CompanyId, filter);
return View("View", response);
}
}
}
Assuming that AssetDomain is a polymorphic type, you can now write a test and inject a Test Double:
[Fact]
public void MyTest()
{
var testDouble = new AssetDomainTestDouble();
var sut = new ProbablySomeController(testDouble);
var actual = sut.Index(42, AssetFilterType.All);
// Put assertions here
}
step1 : Required library
step 2 : When the application starts , register required domain like
protected void Application_Start()
UnityConfig.RegisterComponents();
Step 3: create one static class and register all your domain
example
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
Initialize domain which will injected in controller
container.RegisterType<IPricingDomain, PricingDomain>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
step 4 :
so you can inject respective interface in constructor
in controller file.
goal : get rid of below any pattern in your project.
and start writing unit test cases.

How to do Setup of mocks with Ninject's MockingKernel (moq)

I'm having a really hard time trying to figure how I can do .SetupXXX() calls on the underlying Mock<T> that has been generated inside the MockingKernel. Anyone who can shed some light on how it is supposed to work?
You need to call the GetMock<T> method on the MoqMockingKernel which will return the generated Mock<T> on which you can call your .SetupXXX()/VerifyXXX() methods.
Here is an example unit test which demonstrates the GetMock<T> usage:
[Test]
public void Test()
{
var mockingKernel = new MoqMockingKernel();
var serviceMock = mockingKernel.GetMock<IService>();
serviceMock.Setup(m => m.GetGreetings()).Returns("World");
var sut = mockingKernel.Get<MyClass>();
Assert.AreEqual("Hello World", sut.SayHello());
}
Where the involved types are the following:
public interface IService { string GetGreetings(); }
public class MyClass
{
private readonly IService service;
public MyClass(IService service) { this.service = service; }
public string SayHello()
{
return string.Format("Hello {0}", service.GetGreetings());
}
}
Note that you can access the generated Moq.MockRepository (if you prefer it over the SetupXXX methods) with the MoqMockingKernel.MockRepository property.

DI in Service Contract WCF

Please find below my code. Employee class implements IEmployee interface.
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> emp = new List<IEmployee>();
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(IEmployee));
TempObject.EmployeeId = "12345678";
emp.Add(TempObject);
return emp;
}
}
}
As is visible the above code does compile but wont work because interface instance cannot be created.How can I achive DI(Dependency Injection) here...If I write..
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee));
Then this class will be dependent not only on the Interface but also the class...assuming that one fine day Employee class becomes Employee2.There will be code changes at two places..
1)[ServiceKnownType(typeof(MiddleWare.Classes.Employee2))]
2)IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee2));
I want to avoid that. Can we do something at implementation of IOperationBehavior or is there a Ninject way of achieving this or am I trying to achieve impossible?
Consider a design change - Use the factory pattern to create an instance of your employee.
public EmployeeFactory : IEmployeeFactory
{
public IEmployee CreateEmployee()
{
return new Employee();
}
}
And introduce a dependency on the Factory from your middleware, so creating a new IEmployee becomes:
public class Miscellaneous : IMiscellaneous
{
private readonly IEmployeeFasctory _employeeFactory;
public class Miscellaneous(IEmployeeFactory employeeFactory)
{
_employeeFactory = employeeFactory;
}
public IEnumerable Search_Employee (string searchText)
{
List employees = new List();
IEmployee employee = _employeeFactory.CreateEmployee();
employee.EmployeeId = "12345678";
employees.Add(TempObject);
return employees;
}
And then you can inject your EmployeeFactory into Miscellaneous. And should Employee one day become deprecated and Employee2 comes along, just change the factory!
As rich.okelly points out in another answer, IEmployeeFactory should be used to create instances of the IEmployee interface, since IEmployee isn't a Service, but an Entity.
The IEmployeeFactory interface, on the other hand, is a Service, so should be injected into the service class using Constructor Injection. Here's a write-up of enabling Constructor Injection in WCF.
Had a discussion within the team.
1) Constructor based implementation is not comfortable..The service would be IIS hosted and consumed as a web-reference.Cannot ask client systems to provide FactoryImplementatedObjects in Miscellaneous class call.
2) Entity based factories is also not absolutely accurate.If I happen to have say 20 specific entities in my project like Employee,Material,Project,Location,Order then I need to have 20 Factories.Also the Miscellaneous class will have several custom constructors to support specific contract calls..
I have prepared a system which is working and DI is achieved to a great level but I feel like I am cheating OOPS..Doesnt feel correct at heart..but cannot be refuted to be wrong..Please check and let me know your comments.
I now have a IEntity Interface which is the base for all other Entities.
namespace BusinessModel.Interfaces
{
public interface IEntity
{
string EntityDescription { get; set; }
}
}
Hence forth all will implement this.
namespace BusinessModel.Interfaces
{
public interface IEmployee : IEntity
{
string EmployeeId { get; set ; }
}
}
namespace BusinessModel.Interfaces
{
public interface IProject : IEntity
{
string ProjectId { get; set; }
}
}
and so on..(Interface implementing interface..absolutely ridiculous,cheating but working)
Next,An Enum type is declared to have a list of all Entities...
namespace MiddleWare.Common
{
internal enum BusinessModel
{
IEmployee,
IProject
}
}
A DI Helper class is created which will henceforth be considered a part of Business Model and any changes to it (Implementation,Naming..) would be taken as a Business Shift.So if DIHelper class has to become DIHelper2 then this is like BIG.(Can this also be avoided??)
namespace MiddleWare.Common
{
internal sealed class DIHelper
{
internal static IEntity GetRequiredIEntityBasedObject(BusinessModel BusinessModelObject)
{
switch (BusinessModelObject)
{
case BusinessModel.IEmployee:
return new Employee();
}
return null;
}
}
}
Function is Self Explanatory...
So now finally,the contract and implementation...
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> IEmployeeList = new List<IEmployee>();
IEmployee TempObject = (IEmployee)DIHelper.GetRequiredIEntityBasedObject(MiddleWare.Common.BusinessModel.IEmployee);
TempObject.EmployeeId = "12345678";
IEmployeeList.Add(TempObject);
return IEmployeeList;
}
}
}
What do you say??
My Team is happy though :)
From your updated requirements, there is nothing related to DI in this question...
So, to create a type based on the service known types of a service contract you can use:
public class EntityLoader<TServiceContract>
{
private static readonly HashSet<Type> ServiceKnownTypes = new HashSet<Type>();
static EntityLoader()
{
var attributes = typeof(TServiceContract).GetMethods().SelectMany(m => m.GetCustomAttributes(typeof(ServiceKnownTypeAttribute), true)).Cast<ServiceKnownTypeAttribute>();
foreach (var attribute in attributes)
{
ServiceKnownTypes.Add(attribute.Type);
}
}
public TEntity CreateEntity<TEntity>()
{
var runtimeType = ServiceKnownTypes.Single(t => typeof(TEntity).IsAssignableFrom(t));
return (TEntity)Activator.CreateInstance(runtimeType);
}
}
Which is then useable like so:
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(Employee))]
IEnumerable<IEmployee> SearchEmployee(string SearchText);
}
public class Miscellaneous : IMiscellaneous
{
private readonly EntityLoader<IMiscellaneous> _entityLoader = new EntityLoader<IMiscellaneous>();
public IEnumerable<IEmployee> SearchEmployee(string SearchText)
{
List<IEmployee> employees = new List<IEmployee>();
IEmployee employee = _entityLoader.CreateEntity<IEmployee>();
employee.EmployeeId = "12345678";
employees.Add(employee);
return employees;
}
}
Obviously, the above code assumes that ALL of your service entities will contain public parameterless constructors and that there will only be one ServiceKnownType that implements each interface.

AutoMapper testing and dependency injection for resolvers

Im writing a test for an automapper map. One of the destination members in the map requires a value resolver, and that value resolver has service dependencies which are injected. I want to use the real implementation for the resolver (since thats part of the map im testing) but Id like to use mocks for the dependencies the resolver has.
Ofcourse I want to try to avoid using an ioc container for in my tests, but how do I easily resolve my value resolver's dependencies without one?
This is my rather simplified example, in the real case there are several resolvers with sometimes many dependencies, and I really dont like to basically implement my own dependency resolver in my tests. Should I use a lightweight ioc container?
[TestFixture]
public class MapperTest
{
private IMyService myService;
[SetUp]
public void Setup()
{
Mapper.Initialize(config =>
{
config.ConstructServicesUsing(Resolve);
config.AddProfile<MyProfile>();
});
}
public T Resolve<T>()
{
return (T) Resolve(typeof (T));
}
public object Resolve(Type type)
{
if (type == typeof(MyValueResolver))
return new MyValueResolver(Resolve<IMyService>());
if (type == typeof(IMyService))
return myService;
Assert.Fail("Can not resolve type " + type.AssemblyQualifiedName);
return null;
}
[Test]
public void ShouldConfigureCorrectly()
{
Mapper.AssertConfigurationIsValid();
}
[Test]
public void ShouldMapStuff()
{
var source = new Source() {...};
var child = new Child();
myService = MockRepository.GenerateMock<IMyService>();
myService .Stub(x => x.DoServiceStuff(source)).Return(child);
var result = Mapper.Map<ISource, Destination>(source);
result.Should().Not.Be.Null();
result.Child.Should().Be.SameInstanceAs(child);
}
}
public class MyProfile : Profile
{
protected override void Configure()
{
base.Configure();
CreateMap<ISource, Destination>()
.ForMember(m => m.Child, c => c.ResolveUsing<MyResolver>());
}
}
public class MyResolver: ValueResolver<ISource, Destination>
{
private readonly IMyService _myService;
public MyResolver(IMyService myService)
{
_myService = myService;
}
protected override Child ResolveCore(ISource source)
{
return _myService.DoServiceStuff(source);
}
}
}
Here's one solution, but basically its what iv done already:
http://groups.google.com/group/automapper-users/browse_thread/thread/aea8bbe32b1f590a/f3185d30322d8109
The suggestion is to use a service locator which are set up differently depending on test or real implementation.

Ninject Cascading Inection with IList

I am trying to use Ninject to implement cascading injection into a class that contains an IList field. It seems that, unless I specifically specify each binding to use in the kernel.Get method, the IList property is always injected with a list of a single default object.
The following VSTest code illustrates the problem. The first test fails because the IList field contains one MyType object with Name=null. The second test passes, but I had to specifically tell Ninject what constructor arguments to use. I am using the latest build from the ninject.web.mvc project for MVC 3.
Does Ninject specifically treat IList different, or is there a better way to handle this? Note that this seems to only be a problem when using an IList. Createing a custom collection object that wraps IList works as expected in the first test.
[TestClass()]
public class NinjectTest
{
[TestMethod()]
public void ListTest_Fails_NameNullAndCountIncorrect()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>();
var actual = target.GetList();
// Fails. Returned value is set to a list of a single object equal to default(MyType)
Assert.AreEqual(2, actual.Count());
// Fails because MyType object is initialized with a null "Name" property
Assert.AreEqual("Fred", actual.First().Name);
}
[TestMethod()]
public void ListTest_Passes_SeemsLikeUnnecessaryConfiguration()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>(new ConstructorArgument("myGenericObject", kernel.Get<IGenericObject<MyType>>(new ConstructorArgument("myList", kernel.Get<IList<MyType>>()))));
var actual = target.GetList();
Assert.AreEqual(2, actual.Count());
Assert.AreEqual("Fred", actual.First().Name);
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IList<MyType>>().ToConstant(new List<MyType> { new MyType { Name = "Fred" }, new MyType { Name = "Bob" } });
Bind<IGenericObject<MyType>>().To<StubObject<MyType>>();
}
}
public class MyModel
{
private IGenericObject<MyType> myGenericObject;
public MyModel(IGenericObject<MyType> myGenericObject)
{
this.myGenericObject = myGenericObject;
}
public IEnumerable<MyType> GetList()
{
return myGenericObject.GetList();
}
}
public interface IGenericObject<T>
{
IList<T> GetList();
}
public class StubObject<T> : IGenericObject<T>
{
private IList<T> _myList;
public StubObject(IList<T> myList)
{
_myList = myList;
}
public IList<T> GetList()
{
return _myList;
}
}
public class MyType
{
public String Name { get; set; }
}
lists, collections and arrays are handled slightly different. For those types ninject will inject a list or array containing an instance of all bindings for the generic type. In your case the implementation type is a class which is aoutobound by default. So the list will contain one instance of that class. If you add an interface to that class and use this one the list will be empty.