This question is pertaining to the usage of MEF.
I want to provide different values for the same import in these two scenarios
[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
[Import("B")]
public IB B;
}
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
[Import]
public IB B;
}
In both of the two scenarios above, I want to satisfy the import of IB with different values that is when I do this in the first type of export
var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");
or this in the second export
var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();
I want the two instance of A a1 and a2 to have different values of IB. I don't want to use ImportMany because then I have to decide which one to choose and I want to keep that logic out of class A.
The two scenarios related to these exports are that I want to have a common generic view to work with different types of view models implementing some interface and different instances of a class that provides some service to be configured with different configuration parameters.
Perhaps you are looking for something like this?
public class AExporter
{
[Export("A1", typeof(IA)]
public IA A1
{
get
{
return new A(this.B1);
}
}
[Export("A2", typeof(IA)]
public IA A2
{
get
{
return new A(this.B2);
}
}
[Import("B1", typeof(IB))]
public IB B1 { private get; set; }
[Import("B2", typeof(IB))]
public IB B2 { private get; set; }
}
However, MEF isn't really designed for such fine-grained control over the composition. You could try an alternative like Autofac, which integrates well with MEF.
I don't entirely understand what you are trying to do, but I think you may be able to do it by specifying a creation policy of NonShared on the IB import.
[Import(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IB B;
Related
In my projects, I often have many static Objects of a class (let's say class A).
I create an additional class B to store the static Objects of class A, because else it would be too messy to store all static Objects in their own class:
public class A{
public A(...){
...
}
}
public class B{
public static A a1 = new A(...);
public static A a2 = new A(...);
public static A a3 = new A(...);
...
}
Then I access these Objects with B.a1, B.a2, ...
Is there a better way to store a large number of Objects?
This is a bit too general to answer. Why exactly do you need these static instances?
If it's a small number of commonly used instances, it really makes the most sense for them to be within the class itself. Look at BigInteger, which has static instances for 0, 1, and 10 within the class.
I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}
I'm using an automapper to flatten the object coming from WS. Simplified model would be as follows:
public abstract class AOrder {
public Product Product {get;set;}
public decimal Amount {get;set;}
//number of other properties
}
public abstract class Product {
//product properties
}
public class RatedProduct : Product {
public int Rate { get;set;}
}
public class MarketOrder : AOrder {
//some specific market order properties
}
Using automapper I'm trying to flatten this into:
public class OrderEntity {
public decimal Amount {get;set;}
public int ProductRate {get;set;}
}
with next mapping:
CreateMap<RatedProduct, OrderEntity>();
CreateMap<MarketOrder, OrderEntity>();
The above mapping will not map the ProductRate.
Atm I've just used the AfterMap:
CreateMap<MarketOrder, OrderEntity>()
.AfterMap((s,d) => {
var prod = s.Product as RatedProduct;
if (prod != null)
{
//map fields
}
});
which works pretty well, but thought if I could reuse the automapper flattening possibilities (i.e. matching by name) I wouldn't need to apply the after map in quite many places.
Note: I can't change the WS and this is just a tiny part from object hierarchy.
Advice appreciated.
Mapping Rate to ProductRate is fairly straight forward with "ForMember"
The one where you have to do a cast to the specific type to see if it is that type is a little trickier but I think the same approach you took is what you might have to do however I don't think you need to do "aftermap". I thought all your destination mappings had to be found OR you need to mark them as ignore of the mapping will fail.
Another thing you could do is just change the OrderEntity.ProductRate to be OrderEntity.Rate. Then it would find it and map it for you except where it was hidden because Product doesn't have a rate (but RatedProducts do).
public class OrderEntity {
public decimal Amount {get;set;}
public int Rate {get;set;} //changed name from ProductRate to just Rate.
}
Mapper.CreateMap<Product, OrderEntity>()
.Include<RatedProduct, OrderEntry>();
Mapper.CreateMap<RatedProduct, OrderEntry>();
SEE: Polymorphic element types in collections
I'm trying to avoid ending up with an anaemic Domain Model, so I'm attempting to keep as much logic as possible within the domain model itself. I have a method called AddIngredient, which needs to add a new KeyedObject to my Recipe Aggregate.
As the Domain Models themselves are meant to be devoid of repositories, I'm getting the ingredient via a business rule class:
public class Recipe : AggregateObject
{
public void AddIngredient(int ingId, double quantity)
{
GetIngredientMessage message = new GetIngredientMessage();
message.IngredientId = ingId;
GetIngredient handler = ServiceLocator.Factory.Resolve<GetIngredient>();
Ingredient ingredient = handler.Execute(message);
Ingredients.Add(new OriginalIngredient()
{
Ingredient = ingredient,
Quantity = quantity
});
}
}
As you can see, I'm using a line the line ServiceLocator.Factory.Resolve<GetIngredient>(); to obtain my GetIngredient business rule class. GetIngredient is a simple command handler that looks like the following:
public class GetIngredient : ICommandHandler<Ingredient, GetIngredientMessage>
{
private readonly IIngredientRepository _ingredientRepository;
public GetIngredient(IIngredientRepository ingredientRepository)
{
_ingredientRepository = ingredientRepository;
}
}
I assign my IoC factory class to the ServiceLocator.Factory, so the Domain has the ability to use its own interfaces, without seeing the concrete class implementation:
ServiceLocator.Factory = new IoCFactory();
I'm pretty sure I'm doing something wrong as it all feels a little bit bodge-like.
Can anyone spot anything blatantly wrong?
Is there a more appropriate way to instantiate a business rule handler such as GetIngredient without a static reference to my IoC Factory?
I suggest you introduce another layer into the design -- the Application layer. This layer responsibility would be to translate commands (either explicitly encapsulated in command objects or passed implicitly as int ingId, double quantity) into domain model invocations (Recipe.AddIngredient).
By doing so you'll move the responsibility of finding an ingredient by its id to a layer above domain, where you can safely make use of repositories directly without introducing unwanted coupling. The transformed solution would look something like this:
public class ApplicationLayer
{
private readonly IRecipeRepository _recipeRepository;
private readonly IIngredientRepository _ingredientRepository;
/*
* This would be called by IoC container when resolving Application layer class.
* Repositories would be injected by interfacy so there would be no coupling to
* concrete classes.
*/
public ApplicationLayer(IRecipeRepository recipeRepository, IIngredientRepository ingredientRepository)
{
_recipeRepository = recipeRepository;
_ingredientRepository = ingredientRepository;
}
public void AddIngredient(int recipeId, int ingId, double quantity)
{
var recipe = _recipeRepository.FindById(recipeId);
var ingredient = _ingredientRepository.FindById(ingId);
recipe.AddIngredient(ingredient, quantity);
}
}
And the now simplified Recipe class would look something like this:
public class Recipe : AggregateObject
{
public void AddIngredient(Ingredient ingredient, double quantity)
{
Ingredients.Add(new OriginalIngredient()
{
Ingredient = ingredient,
Quantity = quantity
});
}
}
Hope that helps.
If you're in a team and a programmer gives you an interface with create, read, update and delete methods, how do you avoid type switching?
Quoting Clean Code A Handbook of Agile Software Craftsmanship:
public Money calculatePay(Employee e)
throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
There are several problems with this function. First, it’s large, and when new
employee types are added, it will grow. Second, it very clearly does more than one thing.
Third, it violates the Single Responsibility Principle7 (SRP) because there is more than one reason for it to change. Fourth, it violates the Open Closed Principle8 (OCP) because it must change whenever new types are added. But possibly the worst problem with this
function is that there are an unlimited number of other functions that will have the same
structure. For example we could have
isPayday(Employee e, Date date),
or
deliverPay(Employee e, Money pay),
or a host of others. All of which would have the same deleterious structure.
The book tells me to use the Factory Pattern, but in way that it makes me feel that I shouldn't really use it.
Quoting the book again:
The solution to this problem (see Listing 3-5) is to bury the switch statement in the
basement of an ABSTRACT FACTORY,9 and never let anyone see it.
Is the switch statement ugly?
In reality, the employee object should have its own calculate pay function that will give you the pay. This calculate pay function would change based on what type of employee it was.
That way it is up to the object to define the implementation, not the user of the object.
abstract class Employee
{
public abstract function calculatePay();
}
class HourlyEmployee extends Employee
{
public function calculatePay()
{
return $this->hour * $this->pay_rate;
}
}
class SalariedEmployee extends Employee
{
public function calculatePay()
{
return $this->monthly_pay_rate;
}
}
When you build the Factory, THEN you do the switch statement there, and only once, to build the employee.
Lets say Employee was in an array, and the type of employee was held in $array['Type']
public function buildEmployee($array)
{
switch($array['Type']){
case 'Hourly':
return new HourlyEmployee($array);
break;
case 'Salaried':
return new SalariedEmployee($array);
break;
}
Finally, to calculate the pay
$employee->calculatePay();
Now, there is no need for more than one switch statement to calculate the pay of the employee based on what type of employee they are. It is just a part of the employee object.
Disclaimer, I'm a minor, so I'm not completely positive on how some of these pays are calculated. But the base of the argument is still valid. The pay should be calculated in the object.
Disclaimer 2, This is PHP Code. But once again, the argument should be valid for any language.
You can totally remove the switch by using a Map of some kind to map the type of an employee to it's corresponding pay calculator. This depends on reflection and is possible in all languages I know.
Assuming the pay calculation is not a responsibility of an employee, we have an interface PayCalculation:
interface PayCalculation {
function calculatePay(Employee $employee);
}
There's an implementation for each category of employee:
class SalariedPayCalculator implements PayCalculation {
public function calculatePay(SalariedEmployee $employee) {
return $employee.getSalary();
}
}
class HourlyPayCalculator implements PayCalculation {
public function calculatePay(HourlyEmployee $employee) {
return $employee.getHourlyRate() * e.getHoursWorked();
}
}
class CommissionedPayCalculator implements PayCalculation {
public function calculatePay(CommissionedEmployee $employee) {
return $employee.getCommissionRate() * $employee.getUnits();
}
}
And the pay calculation would work something like this. Reflection becomes important for this to look at an object and determine it's class at run-time. With this, the switch loop can be eliminated.
public class EmployeePayCalculator implements PayCalculation {
private $map = array();
public function __construct() {
$this->map['SalariedEmployee'] = new SalariedPayCalculator();
$this->map['HourlyEmployee'] = new HourlyPayCalculator();
$this->map['CommissionedEmployee'] = new CommissionedPayCalculator();
}
public function calculatePay(Employee $employee) {
$employeeType = get_class($employee);
$calculator = $this->map[$employeeType];
return $calculator->calculatePay($employee);
}
}
Here we are initializing the map in the constructor, but it can easily be moved outside to an XML configuration file or some database:
<payCalculation>
<category>
<type>Hourly</type>
<payCalculator>HourlyPayCalculator</payCalculator>
</category>
<category>
<type>Salaried</type>
<payCalculator>SalariedPayCalculator</payCalculator>
</category>
...
</payCalculation>
I read it somewhere, that if you're using a switch, then it's suspect that there's too much variation. And when we have too much variation, we should try to encapsulate the variation behind an interface, thereby decoupling the dependencies between objects. Having said that, I think that you should try to create an SalaryType lightweight base class object that will encapsulate this type of logic. Then you make it a member of class Employee and rid yourself of the switch construct. Here's what I mean in a nutshell:
abstract class SalaryType
{
function calculatePay() {}
}
class CommissionedType extends SalaryType
{
function calculatePay() {}
}
class HourlyType extends SalaryType
{
function calculatePay() {}
}
class SalaryType extends SalaryType
{
function calculatePay() {}
}
class Employee
{
private $salaryType;
public function setType( SalaryType emp )
{
$this->salaryType = emp;
}
public function calculatePay()
{
$this->salaryType->calculatePay();
}
}
Btw, a lot of your example code does not seem very "PHP-ish". There are no return types in PHP nor is there really any type safety. Keep in mind also that PHP is not truly polymorphic, so some of the polymorphic behavior found in typical type-safe languages may not work as expected here.