What are Up and Down functions in controllers? - model-view-controller

I see use of Up and Down (aka setUp, tearDown) functions in MVC environments. What do they mean?

Your question needs some better definition, but in general these methods usually indicate that some other framework or resource is in control of the lifecycle of the object you are in. They act as leaf methods, invoked by the framework (in the case if a JUNit test) after the test framework has created all the required plumbing and instantiated your test. Since you don't get to create your own constructor, the framework will invoke setUp() for you. Any code you would have normally placed in a constructor would go here. The opposite is true of teardown. You are not controlling the lifecycle of some object, but you may have created or consumed shared resources that need to be unallocated or returned before the end of the life of the object. The tearDown method is an indicator you should release resources and prepare your object to close up shop (so to speak)

Related

Why do we need the Abstract Factory pattern?

I am reading the chapter 11 page number 90 of clean architecture.
I agree with author that we should use interfaces instead of depending upon the volatile concrete classes to avoid the source code dependency on the concrete class to make our code more modular. He mentions the below pattern to handle the volatile dependency in the code.
In the above image author suggest to use the FactoryServiceImpl to create the instance of the ConcreteImpl.
What's the advantage we get in using the FactoryService? Anyway in the main method we will have to create the instance of FactoryServiceImpl and pass to the Application. Instead we can directly create the instance of the ConcreteImpl and pass it to the Application?
What's the advantage we get in using the FactoryService?
The application does not depend on FactoryServiceImpl nor ConcreteImpl. The advantage is that if you want to test the application class you can easily mock the FactoryService just by providing a test/mock implementation.
Since the application class does not depent on the concrete implentations, it is also not dependent on the dependencies of those classes. E.g. the FactoryServiceImpl might contain a dependency to an external service that it passes to the ConcreteImpl when it creates it - could also be a database. Maybe the FactoryServiceImpl uses a fancy framework that you don't want the application to "indirectly" depent upon.
Anyway in the main method we will have to create the instance of FactoryServiceImpl and pass to the Application. Instead we can directly create the instance of the ConcreteImpl and pass it to the Application?
Yes you could create a ConcreteImpl and pass it to the application, BUT Uncle Bob talks about volatile objects in chapter 11. This means that the application creates ConcreteImpl on the fly when it needs it. Maybe a ConcreteImpl is stateful and belongs to a user request. It might also be possible that the factory takes arguments that it uses to create a ConcreteImpl and this arguments change depending on the application state. Thus the application must create a new ConcreteImpl whenever the this state changes. Thus you can not create one instance in the "main" method.

Single instance of an object per transaction

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.
ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

Per-Request DependencyResolver in Web API

In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.

Castle Windsor Component dependencies and lifestyles

I'm wondering what the best practice is for Castle Windsor component dependency lifestyles. For example if I have a Repository class that is dependent on an ISession. If the Repository is set as PerWebRequest, but the ISession is set as transient, will this pose any problems for the windsor releasing the components so the GC can correctly clean up?
Logically this seems like it will work, because every request for a Repository during the webrequest will get a reference to the same instance. That instance will hold a reference to the single ISession that was instantiated to satisfy the Repo dependency when it was first requested. Windsor will know when the Repo is out of scope due to the PerWebRequest tracking, and thus should know when to clean up the ISession.
However, this post by Krzysztof Koźmic implies that you shouldn't have a component dependent on something with a shorter lifestyle than itself.
[edit]
My question is, is it acceptable to have a Windsor Component depend on something with a shorter lifestyle than itself (i.e. PerWebRequest component -> Transient component)?
Yes, it can be perfectly fine, especially in case of something --> transient. The things you need to worry about is:
am I forcing this component to live (and stay in memory) longer than it should?
am I not going to end up in a situation where the object I depend on gets released automatically (like in case of a singleton that depends on a per-web-request object, which gets released when the first web request ends). In that case you will end up using object in an invalid state, which depending on how you implement it will either throw an exception (fail fast) or misbehave (you don't want to be there).
If you've considered those two, and potentially a number of other factors specific to your scenario, you're in a good position to make an informed choice to press on with the dependency.
Alternatively you can make it a transitive dependency via a layer of indirection:
singleton -(depends on)-> singleton factory -(resolves)-> per-web-request component.
A singleton object may depend on a factory which it uses to pull, say, per-web-request objects that it uses to do its job. With that, if implemented properly, it won't have the drawbacks discussed above.
Hope that helps.
Oh, and the other answer of mine, you linked to in your question - it says rule of thumb, not strict law. It's probably right in majority of cases, but, as discussed above, it's fine to break it if you know what you're doing. That's also the reason why Windsor's diagnostic for detecting those cases is called Potentially misconfigured components
Why would you have multiple sessions in one web request. One pattern I commonly use in web applications regarding sessions is the Unit of Work pattern. Where the web request is the unit of work.
Transient lifestyle is only released when you explicitly release it or its parent(s). Therefore having a transient component that is a dependency for a component with a per web request lifestyle should be fine.

Test Driven Development For Complex Methods involving external dependency

I am implementing a Service Contract for WCF Service.
As per TDD I wrote a test case to just pass it using hardcoded values.
After that I started to put real logic into my Service implementation. The actual logic relies on 3-4 external service and database.
What should I do to my original test case that I wrote ?
If i Keep it same in order to make test pass it will have to call several other external services.
So I have question in general what should I do if I write a test case for a Business Facade first using TDD and later when I add real logic, if it involves external dependency.
Utilize a mocking framework (with dependency inversion or just a factory) so you can inject fake dependencies into the object. These can then then just return canned responses and/or be checked that the class utilizes the dependencies how you intended.
As an example, if your code calls a repository to save, we don't really care in the business method test that the repository did actually save to a persistance store, only that it got called and returned some data if required. What you're really testing is how your code reacts to what the dependency returned, or if it was utilzed correctly - but not the dependency's actual functionality
Ideally the first test should have been representative of how the class/method will work and return data, so the test would still be valid once you're finished.

Resources