asp.net mvc3, why do I need to constructors for my controller class - asp.net

I am learning asp.net mvc3. one example I found online is to show me how to use IOC.
public class HomeController : Controller
{
private IHelloService _service;
public HomeController():this(new HelloService())
{}
public HomeController(IHelloService service)
{
_service = service;
}
}
there are two constructors in this example. I understand the second one. the first one I understand what that for, but to me, it seems like extra code, you will never need it.
can someone please explain to me whats the point to add the first constructor.
public HomeController():this(new HelloService())
{}

When the MVC Framework instantiates a controller, it uses the default (parameter-less) constructor.
By default, you are injecting a concrete IHelloService implementation. This will be used when a user navigates to the action.
Unit Tests would use the overload and pass in the mock IHelloService implementation rather than calling the default constructor.

It can be useful if you don't use a dependency injection framework that injects this for you. In this way you never have to manually inject the object, the object will handle that by itself.
The second constructor is, of course, useful to inject custom objects when unit testing.
Normally one would need to do this:
IFoo foo = new Foo();
IBar bar = new Bar(foo);
When your constructor creates a default object you can just do this:
IBar bar = new Bar();
Bar will then create a Foo and inject it into itself.

Related

The correct way of using UnitOfWork in Repository Pattern

I'm trying to follow a tutorial on using the unit of work and repository pattern on MSDN but I've stumbled at the below:
private UnitOfWork unitOfWork = new UnitOfWork();
"This code adds a class variable for the UnitOfWork class. (If you were using interfaces here, you wouldn't initialize the variable here; instead, you'd implement a pattern of two constructors"
Basically, I need to call my UnitOfWork class in my LogController without actually using the above code as I'm using an interface? How is this possible? I'm not sure what it means by 'two constructors'.
Any advice would be appreiciated
In your class you define
Private IUnitOfWork _unitOfWork = null;
And you have one constructor which accepts an IUnitOfWork so the caller can pass in an implementation:
Public MyClass (IUnitOfWork unitOfWork) {
_unitOfWork = unitOfWork;
}
And you have another which does not, but knows how to go and find which implementation to create. Either it can use a default implementation, or it can go to some config file you've written to define which type to use, etc.
Within the MyClass you still call _unitOfWork.whateverMethod()

Spring Autowiring by variable name

Below is my controller. My program generates an output, based on a form input. Across the project, there are multiple input forms, that generate the output object. So, the essential flow is the same. So I want a single multi-action controller that does all of that.
Challenges:
1. The service classes change. Although all services implement the same interface, and controller calls the same interface method.
2. The input objects change. Although the input objects do not have any methods other than setters, and getters. So I let them all implement an empty interface.
Questions:
How do I change the qualifier, based on the path. Can I use path variables?
Suppose the path has this value -> singleton. Then my corresponding bean names would be singletonService and singletonInput. I want to make a constant class that has stores this mapping information. So, can I call that from inside the qualifier, using some Spring Expression Language? Example, instead of Qualifier(variablePathName) -> Qualifier(getQualifierName['variablePathName']) Something like that?
Please also clarify the theory behind this. From what I understand, beans are created, autowired before the Request are mapped... Does this mean that what I'm trying to achieve here is simply not possible. In that case, would you suggest making Controller-service pairs for handling each request, with basically the same code? But I feel there must be some way to achieve what I'm trying...
Code:
#Cotroller
#RequestMapping(value="/generate/{path}")
public class TestController {
#Autowired
#Qualifier(......)
private IService service;
#Autowired
#Qualifier(......)
IUserInput userInput;
#RequestMapping(method = RequestMethod.POST)
//Some handler method
}
You're right in that the autowiring is all done once up front (point 3). You wouldn't be able to achieve what you want using fields annotated #Autowired and #Qualifier - as these fields would always reference the same bean instance.
You may be better to ask Spring for the particular service bean by name - based on the path variable. You could do it within a single controller instance. For example:
#Cotroller
#RequestMapping(value="/generate/{path}")
public class TestController {
#Autowired
private ApplicationContext applicationContext;
#RequestMapping(method = RequestMethod.POST)
public String someHandlerMethod(#PathVariable String path) {
IService service = (IService) applicationContext.getBean(path + "Service");
IUserInput userInput = (IUserInput) applicationContext.getBean(path + "UserInput");
// Logic using path specific IService and IUserInput
}
}

Test calls to private methods with moq

I have the following method I need to test with Moq. The problem is that each method called in the switch statement is private, including the PublishMessage at the end. But this method (ProcessMessage) is public. How can I test this so that I can ensure the calls are made depending on the parameter? Note that I'm not testing the private methods, I just want to test the "calls". I'd like to mock these private methods and check if they are called using Setup, but Moq does not support mocking private methods.
public void ProcessMessage(DispenserMessageDataContract dispenserMessage)
{
var transOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, transOptions))
{
switch (dispenserMessage.Type)
{
case DispenserMessageType.AckNack:
UpdateAckNackMessageQueue(dispenserMessage);
break;
case DispenserMessageType.FillRequest:
CreateFillRequestMessageQueue(dispenserMessage);
break;
case DispenserMessageType.FillEvent:
UpdateFillEventMessageQueue(dispenserMessage);
break;
case DispenserMessageType.RequestInventory:
CreateRequestInventoryMessageQueue(dispenserMessage);
break;
case DispenserMessageType.ReceiveInventory:
CreateReceiveInventoryMessageQueue(dispenserMessage);
break;
}
scope.Complete();
}
PublishMessage(dispenserMessage);
}
You will have to change those private methods to atleast protected virtual to mock them and then use mock.Protected to mock them(http://blogs.clariusconsulting.net/kzu/mocking-protected-members-with-moq/). You can't mock private methods.
Moq (and few other frameworks) uses Castle Project's DynamicProxy to generate proxies on the fly at run-time so that members of an object can be intercepted without modifying the code of the class. That interception can only be done on public virtual and protected virtual methods.
See below URL for more information:
http://www.castleproject.org/projects/dynamicproxy/
You could extract the private method in another class and make them public, then mock those with Moq and verify that they have been called.
Moq is for mocking properties and methods declared in interfaces and or abstract properties and methods in classes.
The idea behind Moq-testing is that you test the interactions between your class-under-test and the rest of the world (its dependencies). Moq does this by creating a "mocked" implementation of the interface or a derivative of the abstract class with the abstract methods implemented.
Moq cannot override existing implementation like your private methods. This is not how Moq works.
Either you should test "ProcessMessage" with all possible input and expected output or you should refactor your class to delegate the calls to interface methods that you can mock with Moq. Testing private methods is a bad concept anyway. They are kept private for a reason, which is to hide the implementation such that it can change at will.
I prefer to add additional class (*Helper) and move on all my private methods to public. Then you can easily test your methods directly. I didn't find more elegant way to do that.
In some cases, you may need to alter the behavior of private method inside the class you are unit testing. You will need to mock this private method and make it return what needed for the particular case. Since this private method is inside your class under test then mocking it is little more specific. You have to use spy object.
Spy object
A spy is a real object which mocking framework has access to. Spied objects are partially mocked objects. Some their methods are real some mocked. I would say use spy object with great caution because you do not really know what is happening underneath and whether are you actually testing your class or mocked version of it.
public class PowerMockDemo
{
public Point callPrivateMethod() {
return privateMethod(new Point(1, 1));
}
private Point privateMethod(Point point) {
return new Point(point.getX() + 1, point.getY() + 1);
}
}
Then you will mock the Spy object
Hope that will help you,
Best wishes

Map singleton to Interface using unity framework (config file)

is there is anyway to map/register singleton, using the unity configuration file, and map it to an interface while the singleton doesn't expose any public constructor?
Please advice,
Thanks
You have use a class that exposes an internal (as a minimum) constructor if you want unity to create an instance of it. On the other hand you could write a container extension for unity that can use private constructors via reflection.
Another alternative is to write a custom class that has a public constructor and also implements the interface. It then talks to your singleton, something like:
public class SingletonCreator: ISingleton
{
public int SomeMethodInsideInterface()
{
return RealSingleton.Instance.SomeMethodInsideInterface();
}
I would prefer the extension method though, something like this code (below) should get you into the private constructor. Then you would use this container extension in you config in order to tell unity to use your extension.
ConstructorInfo[] constructors = typeToConstruct..GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Singleton Class in Flex

I have a doubt,.... How would you create a Singleton class in Flex...
Is there any convention like the class name should eb Singleton or it should extend any other class.
How many Singleton class can a project have?
Can anyone say the real time usage of a Singleton class?
I am planning to keep my components label texts in a Singleton class... Is it a good approach.
Can of worms asking about singletons!
There are a few different options about creating singletons mainly due to AS3 not having private constructors. Here's the pattern we use.
package com.foo.bar {
public class Blah {
private static var instance : Blah;
public function Blah( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Blah {
if (!instance) {
instance = new Blah( new SingletonEnforcer() );
}
return instance;
}
...
}
}
class SingletonEnforcer{}
Note that the SingletonEnforcer class is internal so can only be used by the Blah class (effectively). No-one can directly instantiate the class, they have to go through the getInstance() function.
hope I'm not hitting dead horses here :)
(edit: ahh, I'm just repeating phils link)
Gregors singleton implementation does not protect against invoking the constructor with a null value, as in:
var b:Blah = new Blah(null);
You will still have only 1 instance, but invoking the constructor is still possible with the consequences that follows.
If you absolutely must enforce the singleton, the constructor should make sure that the enforcer parameter isn't null.
public function Blah( enforcer : SingletonEnforcer ) {
if(!enforcer){
throw new Error("whoops!");
}
}
You should also be concerned about ApplicationDomain when loading swf files. External swf files that uses the same definitions, may have multiple singleton instances (1 in each separate applicationdomain) if you do not specify that the swf file must be loaded into the existing applicationdomain.
This means that Blah.getInstance() in AAA.swf is not the same instance as Blah.getinstance() in BBB.swf, if AAA.swf loads BBB.swf without a LoaderContext instance that tells the plugin to load BBB.swf into the same ApplicationDomain as AAA.swf
First you can reference a previous question to find out how to create a singleton class. You can find more info from a Yakov Fain presentation as well.
Second question, your project can technology have as may singleton class as you see fit but it will only create 1 instance of each. For example, in the cairngorm architecture you have 3 main singletons: controller, service and model. The number of actual class can very depending on your project.
Finally, A real world solutions would be. You have 2 components that need to talk to each other but you don't want them to know the other exists. Meaning sometimes the components are there and sometimes they are not...so you need them to be loosely coupled. you can uses singletons to pass the data from one component to the other with out "talking" to them directly.
Using singletons is a good approach if you need to pass data around your application from component to component and would like to decouple them from each other.
package com.foo.bar
{
public class MySingleton
{
private static var _instance:MySingleton = new MySingleton;
private var _myName:String;
public static function get instance():MySingleton
{
return _instance;
}
public function set myName(value:String):void
{
_myName = value;
}
public function get myName():String
{
return _myName;
}
}
}
Notice the absence of a constructor here.
Hello you could check out the following of a Flex Singleton Class example on http://www.how-to-code.com/flex/flex-design-patterns/flex-singleton-class.html

Resources