spring cloud contract verifier: Do we have #AutoConfigureRestAssuredMockMvc like #AutoConfigureMockMvc or similar? - spring-cloud-contract

Is it possible to avoid this #Before method to set up RestAssuredMockMvc in all the contract base classes.
#Before
public void setup() {
RestAssuredMockMvc.standaloneSetup(object);
//RestAssuredMockMvc.mockMvc(object);
}
Is there any annotation support to auto configure restassured mockmvc ?.
I can abstract out this method and let base classes to extend but would like to know if there are any other way of doing this setup.

Nope. There isn't. It makes no sense (at least i don't see it yet) to automate the standalone setup cause it can be customized in so many different ways. What could be automated however is the web app context setup. Anyways, I'm not familiar with any automation option for now.

Related

AutoFac / Unity Container - Dependency Injection with multiple implementations

I am going to work with Dependency Injection for a ASP.NET Web API project.
I understand how constructor Dependency Injection works, but i can't resolve how to make the injector choose between two implementations of the same interface. Lets say for an example that we have an interface like this:
public interface ISender
{
void Send();
void AddReceipment(User user);
}
Then lets say i have 2 implementations of this SmsSender and MailSender using the same ISender interface.
Now i have two API controllers lets call them "MailController" and "SmsController".
Now i want the dependency injector to inject ISender into the MailController with the implementation of the class MailSender and in the SmsController i want to inject ISender too, but with the implementation of the class SmsSender.
Is that possible using AutoFac or Unity container?
If it is, then how would i aproach that?
According to the Autofac docs, you have 4 options to achieve this:
Redesign your interfaces
Change the registrations
Use keyed services
Use metadata

Which Pattern to choose ? Asp.net Mvc 4

I'm really confused, I learned with the book "Apress pro Asp.net Mvc 4", that the best pattern for Mvc 4, is the Dependency Injection, ( to put the Model data of the database etc... in another project (Domain) and then create interfaces and implementation to those interfaces, and then connect it to the controller with Ninja..
And all the connect to the db is only from the data-layer solution, the only model in the web solution in viewModel
The Controller
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
this.repository = productRepository;
}
....
}
and Ninject
ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
and on the other hand, In my last job(webmaster) , the company used another pattern for the mvc Projects (I'm using this pattern right now).
the projects is made with only One Solution and using Static Classes to handle the data layer
I don't like the Dependency Injection, this is too complicated, and by 'f12' you see only the interface instead of the Concrete class
Some questions:
which patter is better for performance (fast website)?
is't good to use " public Db db = new Db();" in the controller, instead of use it only in the domain layer (solution)??
What is the advantages of using Dependency Injection? is't bad to use my pattern?
What is the advantages of split the project into 2 solutions for the Data Layer?
example:
public class LanguageController : AdminController
{
public Db db = new Db();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
//
// GET: /Admin/Language/
public ActionResult Index()
{
return View(db.Languages.ToList());
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(short id)
{
Language language = db.Languages.Find(id);
db.Languages.Remove(language);
db.SaveChanges();
return RedirectToAction("Index");
}
...
}
which patter is better for performance (fast website)?
Impossible to answer. You could have non-performant code in either of these approaches. Don't try to prematurely optimize for performance, optimize for clean and supportable code and address performance bottlenecks that are actually observed in real scenarios.
is't good to use " public Db db = new Db();" in the controller, instead of use it only in the domain layer (solution)
It's a question of separating concerns and isolating dependencies. If your controller internally instantiates a connection to a database then that controller can only ever be used in the context of that database. This will make unit testing the controller very difficult. It also means that replacing the database means modifying the controller, which shouldn't need to be modified in that case.
Dependency injection frameworks are simply a way of addressing the Dependency Inversion Principle. The idea is that if Object A (the controller) needs an instance of Object B (the database object) then it should require that the instance be supplied to it, rather than internally instantiate it. The immediate benefit here is that Object B can just be an interface or abstract class which could have many different implementations. Object A shouldn't care which implementation is given to it, as long as it satisfies the same observable behavior.
By inverting the dependency (whether or not you use a dependency injection framework), you remove the dependency on the database from the controller. The controller just handles client-initiated requests. Something else handles the database dependency. This makes these two separate objects more portable and re-usable.
What is the advantages of using Dependency Injection? is't bad to use my pattern?
See above. Dependency injection is a way to achieve inversion of dependencies, which is the core goal in this case. Note that there are a few different ways to achieve this. Some frameworks prefer constructor injection, some support property/setter injection, etc. Personally I tend to go with the service locator pattern, which has the added benefit of being able to abstract the dependency of the dependency injector itself.
It's only "bad" to use your approach if you run into any problems when using it. There are good patterns to address various concerns, but if your project doesn't legitimately have those concerns then using those patterns would be over-engineering and would actually hurt the supportability of the code. So, as with anything, "it depends."
What is the advantages of split the project into 2 solutions for the Data Layer?
Two solutions? Or two projects in the same solution? (Resulting in two assemblies.) The advantage is that you can re-use one without having a dependency on the other. For example, in some of the code you posted there is an allusion to the repository pattern. If you have an assembly which serves only the purpose of implementing repositories to the back-end data then any application can use those repositories. If instead it's all implemented in the MVC application directly then no other application can use it, it's tightly coupled to the MVC application.
If you will never need to re-use that functionality, then this isn't the end of the world. If you would like to re-use that functionality, separating it into a portable assembly which internally isolates its dependencies would allow for that.

What is the most appropriate place for placing (startup) initialization code in a Restlet application?

Where can I embed startup initialization code in a Restlet web application, without using a ServletContextListener?
I wish to have transparent deployment of my Restlet to a web server like JBoss/Tomcat and would like to get rid of the initialization logic in the Listener - so as to be able to conveniently deploy it outside of a web server, if the need be - definitely not for heavy production use, but it's valuable nevertheless.
Would inserting it into org.restlet.Component's constructor ensure that it'll only execute once? Is that the right place to put it?
public class MyComponent extends org.restlet.Component
{
public MyComponent() //constructor
{
//insert initialization code here that should run ONLY ONCE?
this.getDefaultHost().attach(new MyApplication()); // MyApplication extends org.restlet.Application
}
}
I went through the docs and also looked at a similar post: RESTlet startup initialization deprecated? but I'm still not sure if it's the right way. I would like to remove the dependency on the Listener if at all possible.
Using the constructor of the Component is a good place for initialization processing and you can be sure that such processing are only executed once.
You can notice that the method start / stop of the component can also be used in your case. Don't forget to call the super method in them. These methods are called when you start / stop your component that is commonly done once...
Hope it helps you.
Thierry

Is Repository Singleton or Static or None of these?

I have a ASP.NET web site which uses domain driven design and uses repository for its database operations.
I want to know that what is pros and cons of singleton repository and static repository and simple repository class which will new on every access?
further more if anyone can compare and guide me to use which one of them I will be appreciate.
Static and singleton aren't good solution for Repository pattern. What if your application will use 2 or more repositories in the future?
IMO the best solution is to use a Dependency Injection container and inject your IRepository interface in the classes that need it.
I suggest you to read a good book about domain driven design and a good book about dependency injection (like Mark Seeman's Dependency Injection in .NET).
With singletons and static classes your application won't be scalable
You have two singleton repositories:
class Repository<TEntity> {
static Repository<TEntity> Instance { get { ... /*using sql server*/ } }
}
class Repository2<TEntity> {
static Repository2<TEntity> Instance { get { ... /*using WCF or XML or any else */ } }
}
The services using them must have a static reference to one of them or both:
class OrderService {
public void Save(Order order) { Repository<Order>.Instance.Insert(order); }
}
How can you save your order using Repository2, if the repository is statically referenced?
A better solution is using DI:
interface IRepository<TEntity> { ... }
class SqlRepository<TEntity> : IRepository<TEntity> { ....}
class OrderService {
private readonly IRepository<TEntity> _repo;
public OrderService(IRepository<TEntity> repo) { _repo = repo; }
public void Save(Order order) { repo.Insert(order); }
}
Don't use static or singleton repositories because of:
It affects testablility, you can not mock it when unit testing.
It affects extensibility, you can not make more than one concrete implementation and you can not replace behavior without re-compiling.
It affects scalability in terms of lifecycle management, insetead depend on dependency injection framework to inject the dependency and manage lifecycle.
It affects maintainability, it forces dependency upon concrete implementation instead of abstraction.
Bottom line: DONT use static or singleton repositories
instead create repository interfaces in your domain model project, and implement these interfaces in a concrete data access project, and use dependency injection framework.
Two SOLID reasons to not have singleton repository:
Consumers of repository will be coupled to repository implementation. This will negatively affect extensibility and testabiliy. This is a DIP violation. Depend on abstractions, not on concretions.
Repository implementation will have to violate SRP because it will most likely end up managing ORM session, database connection and potentially transactions. It would also have to make thread safe guarantees because it potentially can be used from multiple threads. Instead, database connection (ORM Session) should be injected into repository implementation so that consuming code can arrange multiple repository calls into transaction.
Possible solution to both problems is Constructor Injection.
I personally respectfully disagree with previous answers.
I have developed multiple websites (one with 7 millions page views per month) and never had a single problem with my static repositories.
My static repository implementation is pretty simple and only contains objects providers as properties. A single repository can contain as many providers as you need.
Then, the providers are responsible to manage database connection and transactions. Using TransactionScope, the consumer could manage the transactions or let it to the providers.
Every providers are developed using the singleton pattern.
This way, I can get my objects by simply calling this :
var myObj = MyRepository.MyProvider.GetMyObject(id);
At any time, there is only one repository and one provider of each type in every web pool of my application. Depending on how many users you have at the same time on your site, you could set more than one web pool (but most of the time one is just enough).
I don't see where my repository/providers consumers are coupled with my repository. In fact, the implementations of my providers are totally abstracted from them. Of course, all providers returned by my repository are interfaces and I could easily change the implementation of them at any time and push my new dll on the web server. If I want to create a completely new provider with the same interface, I only have to change it in ONE place: my repository.
This way, no need to add dependency injection or having to create your own ControllerFactory (for MVC procjects).
And you still have the advantage of clean code in your controllers. You will also save a lot of repository creation and destruction every time a page is requested (which normally use reflection in your ControllerFactory).
If you are looking for a scalable solution (if you really need it which most of the time is not really a problem), my way of developing repositories should never be a problem compared to dependency injection.

How to call an EJB method when it deploys itself?

I want to call to a method from an EJB in the same instant in which one deploys itself, without using a servlet.
Thanks.
David.
There seems to be no life-cycle methods defined by the EJB spec for this purpose. Individual vendors may provide extensions to allow this. For example Startup Beans in WebSphere would be a place to put the invocation logic you want.
Using techniques such as a static method seem slightly dangerous in that we don't know whether all dependency injection is complete before that static method fires, and hence whether you can safely use the business methods of the EJB.
Persoanlly, if I needed to be portable I would bite the bullet and use a servlet. It costs very little.
Try doing your initialization within a static block. This will run once when the classloader loads the class.
static { System.out.println("static"); }
The PostConstruct hook is right for that.
Find more info on about PostConstruct here:
in the javadoc
lifecycle of EJBs in the JavaEE 5 tutorial
Let's finish with a quick example:
#Stateless
public class TestEJB implements MyEJBInterface{
#PostConstruct
public void doThatAfterInitialization() {
//put your code here to be executed after creation and initialization of your bean
}
}
Static initializer blocks are technically not illegal in EJB but they are used to execute code before any constructor (which might be a problem) when instantiating a class. They are typically used to initialize static fields which may be illegal in EJB if they are not read only. So, what about using ejbCreate(), setSessionContext() or setEntityContext() methods instead (not even sure this would be appropriate without more details on the problem you are trying to solve)?
The EJB container, for a #Singleton bean, shall create the instance of the bean as soon as the application is deploy if it is annotated #Startup.
That will, of course, fire up static initialization blocks, the constructor, dependency injection setters, #PostConstruct methods etc.
Here is the appropriate referente to the Java EE 6 Tutorial.

Resources