asp.net c# Automap a class from within that class - asp.net-mvc-4

To best describe what I want to happen, i'll show what i'm doing, as to me it makes sense that this would work ...
public class foo()
{
public foo()
{
MyContext db = new MyContext();
foobar = db.foobar.first();
this = Mapper.Map<bar, foo>(foobar);
}
}
Basically, I want to use automapper within the destination class to map from the source class within the destination classes constructor.
Is there a way to do this?

You cannot do this because this is read only in C#. You cannot assign this a value in the constructor. Not cool to try to change the reference of an object in its constructor. You will have to do the mapping manually and assign each individual property. I would also question if it as a good practice to assign an object values from a database or service in a default constructor. It is not very transparent to the user of the object what is going on and you can get an exception in your constructor.

Related

Alternate implementation of Builder Pattern. Anything wrong with this?

Most of the implementations of Builder pattern I have seen are along these lines:
https://github.com/Design-pattrns/Builder-Pattern/blob/master/src/Computer.java
Basically the nested builder class needs to mirror all the attributes of the class that we need to build objects of and then provide methods to set the said attributes and an additional build() method inside the builder class.
When I tried to implement builder on my own, I came up with this (I use an instance of Person object inside builder instead of copying all the attributes of the Person class)
public class Person {
private String firstName;
private String lastName;
public static class PersonBuilder{
private Person person = new Person();
public PersonBuilder firstName(String firstName){
person.firstName = firstName;
return this;
}
public PersonBuilder lastName(String lastName){
person.lastName = lastName;
return this;
}
public Person build(){
return person;
}
}
}
Benefits:
1). No need to repeat the attributes of the class we want to instantiate
2). build method is simplified, just need to return the person object.
3). The Person class need not have a constructor which takes the Builder object as argument
4). More easily "updatable". If new attributes are added to person class, all we need
to do is add the set method inside the builder class if needed. No need to
create another attribute.
Cons:
1). The person object is eager initialised?
So are there any issues with this implementation?
I would say the example above is "simpler" but it has none of the advantages a builder offers and its probably better to just use the new keywords where you need the object and adding the properties to the constructor. Id say the drawbacks compared to the builder are as follows:
it can only make a single instance
once the builder has "finished" it can continue to interact with the object as it still holds a reference to it.
its very tightly coupled to the product it is "building".
the fact that the person class has to expose a lot of properties as mutable for the builder, which you might want to not be mutable elsewhere in the code.
Its actually more of a configurator, I would not advise this pattern however you could pass the object to be configured into the constructor. In which case I would create two interfaces
IConfigurablePerson which includes the setters
IPerson which includes the getters
Give the configurator IConfigurablePerson to its constructor, so it can access the setters then give other classes IPerson with only the getters. The advantage this offers is that it can work with multiple implementations of IConfigurablePerson without needing to know the class its working with (decoupling).

Dozer BeanFactory: How to implement it?

I have looked at the Dozer's FAQs and docs, including the SourceForge forum, but I didn't see any good tutorial or even a simple example on how to implement a custom BeanFactory.
Everyone says, "Just implement a BeanFactory". How exactly do you implement it?
I've Googled and all I see are just jars and sources of jars.
Here is one of my BeanFactories, I hope it helps to explain the common pattern:
public class LineBeanFactory implements BeanFactory {
#Override
public Object createBean(final Object source, final Class<?> sourceClass, final String targetBeanId) {
final LineDto dto = (LineDto) source;
return new Line(dto.getCode(), dto.getElectrified(), dto.getName());
}
}
And the corresponding XML mapping:
<mapping>
<class-a bean-factory="com.floyd.nav.web.ws.mapping.dozer.LineBeanFactory">com.floyd.nav.core.model.Line</class-a>
<class-b>com.floyd.nav.web.contract.dto.LineDto</class-b>
</mapping>
This way I declare that when a new instance of Line is needed then it should create it with my BeanFactory. Here is a unit test, that can explain it:
#Test
public void Line_is_created_with_three_arg_constructor_from_LineDto() {
final LineDto dto = createTransientLineDto();
final Line line = (Line) this.lineBeanFactory.createBean(dto, LineDto.class, null);
assertEquals(dto.getCode(), line.getCode());
assertEquals(dto.getElectrified(), line.isElectrified());
assertEquals(dto.getName(), line.getName());
}
So Object source is the source bean that is mapped, Class sourceClass is the class of the source bean (I'm ignoring it, 'cause it will always be a LineDto instance). String targetBeanId is the ID of the destination bean (too ignored).
A custom bean factory is a class that has a method that creates a bean. There are two "flavours"
a) static create method
SomeBean x = SomeBeanFactory.createSomeBean();
b) instance create method
SomeBeanFactory sbf = new SomeBeanFactory();
SomeBean x = sbf.createSomeBean();
You would create a bean factory if creating and setting up your bean requires some tricky logic, like for example initial value of certain properties depend on external configuration file. A bean factory class allows you to centralize "knowledge" about how to create such a tricky bean. Other classes just call create method without worying how to correctly create such bean.
Here is an actual implementation. Obviously it does not make a lot of sense, since Dozer would do the same without the BeanFactory, but instead of just returning an object, you could initialized it somehow differently.
public class ComponentBeanFactory implements BeanFactory {
#Override
public Object createBean(Object source, Class<?> sourceClass,
String targetBeanId) {
return new ComponentDto();
}
}
Why do you need a BeanFactory anyways? Maybe that would help understanding your question.

Building one object given another

Say I am calling a third-party API which returns a Post, and I want to take that and transfer properties from it into my own Post class. I have in the past had a method like public static my.Post build(their.Post post) which maps the properties how I want.
However, is it better/valid to have a constructor that accepts their.Post and does the property mapping in there? Or should there always be a separate class that does the converting, and leaves my.Post in a more POJO state?
Thanks for your thoughts!
These answers always starts with "it depends."
People generally argue against using public static methods, based on the fact that it is hard to mock them (I don't buy into that bandwagon).
This comes down to design, do you want their post to be part of your class? If you add it as a "copy" constructor then it will now be part of your class and you are dependent on changes to post. If they change their post, your code has to adapt.
The better solution is to decouple it. You would need to find some extenal method to map the two. One way is to use a static builder method (like you mentioned) or if you want to take it a step further, a more complicated solution would be to extract the information you want from their post into some type of generic collection class. Then create a constructor that will accept that constructor class. This way if they change their design your class stays in tact and all you have to do is update the mappings from their post to your generic representation of it.
public class MyPost{
public MyPost(ICollectionOfProperties props){
//copy all properties.
}
}
public static class TheirPostExtensions{
public static ICollectionOfProperties ExtractProperties(this TheirPost thePost){
return new CollectionOfProperties(){
A = thePost.PropA,
B = thePost.PropB
};
}
}
public class Example{
public Example(){
TheirPost tp = new TheirPost();
ICollectionOfProperties props = tp.ExtractProperties();
MyPost mp = new MyPost(props);
}
}

Property chaining in RhinoMocks

I have a class TxRx with a property called Common. Common then has a property called LastMod. I want to write a RhinoMock expectation to show that LastMod has been set with something. So I tried:
var txRx = MockRepository.GenerateMock<TxRx>();
var common = MockRepository.GenerateMock<Common>();
txRx.Expect(t => t.Common).Return(common);
txRx.Expect(t => t.Common.LastMod).SetPropertyAndIgnoreArgument();
But I get the following exception:
System.InvalidOperationException: Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.RhinoMocksExtensions.Expect[T,R](T mock, Function`2 action)
at ...
I presume this means Common needs to be virtual, but as it is a property on a LinqToSql generated class I can't make it virtual (other than hacking the autogen code which is not really an option).
Is there any way around this?
One possibility is to wrap TxRx in a mockable class (i.e. one that has overridable methods and properties which you wish to mock out or implements an interface which defines the properties or methods that you're interested in) and then pass around the wrapper rather than the LinqToSQL class itself.
Perhaps something like the following:
public class TxRxWrapper : ITxRxWrapper
{
private TxRx m_txrx;
public object LastMod
{
get { return m_txrx.Common.LastMod; }
}
...
}
public interface ITxRxWrapper
{
public object LastMod { get; }
...
}
Not ideal (i.e. it can get somewhat cumbersome to pass wrappers around just for mockability!) but that's the only way you can get RhinoMocks to mock properties/methods for you.
The other option is to use TypeMock instead which I believe uses a different mechanism to mock stuff out. I don't think it's free, though.
You would need to replace your second expectation with
txRx.Expect(() => common.LastMod).SetPropertyAndIgnoreArgument();
But the Common property itself needs to be virtual for this to work.

Ensuring only factory can create instance

class XFactory {
private XFactory() {}
static void getX() {
if(...)
return new A(new XFactory());
else
return new B(new XFactory());
}
}
class A {
private A() {}
public A(XFactory xf) {}
}
class B {
private B() {}
public A(XFactory xf) {}
}
By this way I can ensure only Factory can create instances of it's belonging Classes.
Is this right approach or there is any other alternative/good approach?
The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.
I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.
That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.
If you were up for hacks and could not make your constructors private, you could:
Make your factory a global singleton and to create an object:
Create a random key
Add that key to a private list in the factory object of keys in use
Pass the key to the constructor
Have the constructor retrieve the global factory object and call it to validate the key.
If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.
(Do I get hack points?)
Jacob
In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.
public class ExampleClass {
private ExampleClass() {
}
public class NestedFactory {
public ExampleClass createExample() {
return new ExampleClass();
}
}
Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.
I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.