I have this problem...
I have a VS solution with these projects: Persistance, Domain, Services, UI.
Now my problem is that I must reference nhibernate in all project that uses something of nhibernate.
Is it possible that I reference nhibernate only in Persistence project and that any project that have reference to Persistence project can use nhibernate too?
I am using StructureMap as DI container. And I have setup dependency injection through constructor for ISession. So I must reference nhibernate in every layer (not UI) that passes ISession.
What I want is not have nhibernate.dll and all its dependency dll (bytecode.linfu...) referenced in nearly all my projects, but only in persistence. Is this somehow possible?
Thanks
In your Domain projects, you define the interfaces for your data acces objects. Your NHibernate persistence project can reference the Domain project and provide implementation for the data access objects.
Your service project might reference Domain and not Persistence. Your service objects depend on the data access interfaces in Domain. You use your DI container to wire your service objects to the NHibernate implementations in Persistence.
Changing the dependency Domain -> Persistence to Persistence -> Domain is an example of inversion of control.
I can imagine you now have the following service:
using Persistence;
using Domain;
public class UserService
{
private Persistence.NHibernateUserRepository _repository;
public UserService (ISession session)
{
_repository = new Persistence.NHibernateUserRepository(session);
// ...
}
// some service methods
}
I suggest to change this to:
using Domain; // no longer using Persistence package
public class UserService
{
private Domain.IUserRepository _repository;
public UserService (Domain.IUserRepository repo)
{
_repository = repo;
// ...
}
// some service methods
}
In your StructureMap configuration, you configure an NHibernate Session, which you wire to your Persistence.NHibernateUserRepository. Then you wire your UserService to this Persistence.NHibernateUserRepository. I'm not familiar with StructureMap, so I can't help you with the mechanics. You might want to read:
Injecting ISession Into My Repositories Using Structuremap in a Asp.Net MVC Application
http://www.bengtbe.com/blog/post/2009/02/27/Using-StructureMap-with-the-ASPNET-MVC-framework.aspx - this is a post that discusses exactly your problem, including StructureMap, NHibernate and asp.net mvc.
Related
I start working with Spring and have some confusions about its conventions.
Is it fine to put Repositories in Controller?
In a Service class, If I want to reuse code could I inject other Services and other Reposities?
is it the best practice to name Service And Repository class is based on Entity name i.e: User -> UserRepository->UserService?
No, don't use Repositories in the Controller. Only in the Services.
And don't use Entities in your Controller. Create Dto (Data Transfer
Objects) Object from the Entities and work with this in your
frontend
Yes you can use other services and respositories in your service class
Yes it is. Name the interfache UserService and the implementation UserServiceImpl
Check also answer:
It explains the Persistence Bussines and Presentation layers
https://stackoverflow.com/a/34084807/2218992
From various documents and tuts, I've earned and learned following points so far:
Spring Data Rest (SDR) used for exposing our Spring Data Repository as REST service, so that one can use it for self exploring, without any need of creating JAXRS manually. It only works for Repository layer, and we cannot control its way of working in terms of modification or addition other than the configuration using RepositoryRestMvcConfiguration. It uses Spring HATEOAS internally somewhere.
Spring HATEOAS is made for creating links within Entities we return through Controller or REST endpoints. We got ResourceSupport to extend our entity or Resource wrapper class to wrap our Entity to create or add links. There are several Annotations and classes to use such as #EnableHyperediaSupport and EntityLinks.
There may be some points which I am yet to explore or get to know about, but I was just curious about How can we combine SDR into HATEOAS link building process ? Say for eg.
EntityBean bean = repository.findByName(name);
Resource<EntityBean> resource = new Resource<EntityBean>(bean);
//JaxRsLinkBuilder.linkTo(TestResource.class).withRel("entity") // this also works
//ControllerLinkBuilder.linkTo(TestResource.class).withRel("myRel") // this also works
// I am curious how ControllerLinkBuilder and JaxRSLinkBuilder both are working for JaxRS.
//Here TestResource is my REST service class. now in below line:
resource.add(JaxRsLinkBuilder.linkTo(MyRepository.class).withRel("sdf")); //not working
// MyRepository is SDR exposed repository, which I thought should work but not working.
return resource;
So, I just wanted to include my exposed REST repository into manual HATEOAS link building process.. is it possible to do so ?
You should able to use Spring-HATEOAS ResourceProcessor to build links.
Example:
#Component
public class MyBeanResourceProcessor implements ResourceProcessor<Resource<MyBean>> {
#Autowired
private EntityLinks entityLinks;
public Resource<MyBean> process(Resource<MyBean> resource) {
MyBean mybean = resource.getContent();
// Do your linking here using entity class
//EntityBean bean = repository.findByName(name);
//Resource<EntityBean> resource = new Resource<EntityBean>(bean);
// assuming you are linking to a single resource and bean.getId() method... check entitylinks for other methods
//resource.add(entityLinks.linkForSingleResource(bean.class,bean.getId()).withRel("sdf"));
return resource;
}
}
I have experience building applications on the Spring Framework primarily. I was wondering if there was anything similar to the Spring Data API (to support a Data Access Layer) in the JEE6 space?
I know I can wire in an entity manager like:
#PersistenceContext
EntityManager em;
Ideally I would like to avoid writing reams of boiler plate JPA code on Data Access beans, is an API similar to SpringJPA which can help cut down on the amount of boilerplate code such as findAll(), findByX() etc. For example, with SpringJPA I can define a bean as:
#Repository
public interface FooRepository
extends JpaRepository<Foo, String>
{
}
Whereas in vanilla JEE6 I would need a
a FooRepository interface with methods Foo findOne(Long), List<Foo> findAll()
a FooRepositoryImpl which implements the interface and interacts with the EntityManager
Spring Data JPA ships with a CDI extension to simply #Inject a repository into your CDI managed bean. See the reference documentation for details. The approach still requires Spring JARs on the classpath but no container being bootstrapped. This functionality is also available for MongoDB repositories.
I'm currently developing a web application which uses MVC3. the MVC3 project accesses our Application logic through a Service layer. The Service layer accesses the Database using repositories accessed via the UnitOfWork pattern.
I just installed StructureMap to take care of injecting my Services into the MVC3 project. An Example controller would look like this
public class AccountManagementController : Controller
{
IAccountService accountService;
public AccountManagementController(IAccountService accountService)
{
this.accountService = accountService;
}
Now, my problem is that my AccountService class needs to have the UnitOfWork injected when structure map creates it. Currently I handle this by having 2 controllers. One takes an interface, the other instantiates a concrete class.
public class AccountService : IAccountService, IDisposable
{
private IUnitOfWork unitOfWork;
internal AccountService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public AccountService()
{
this.unitOfWork = new UnitOfWork();
}
This seems like code smell to me. Is there a more correct way to handle this?
Thanks,
AFrieze
As Mark suggested I would delete the default constructor, but...
AFAIK, StructureMap choses always the constructor with the most arguments so this should not be an issue while resolving IUnitOfWork dependency.
On the other hand, IDisposable seems to me like a smell. AFAIK structureMap advice how to deal with disposable instances like that :
we should wrap the disposable service into the non disposable
wrapper. the non disposable wrapper should dispose the instance it
wrapps.
we should inject the factory of disposable service to the non disposable wrapper.
In these two cases we inject to the consumers the wrapper insteed of directly injecting the disposable service.
For structureMap we could also take advantage of the nested containers features, which tracks the disposable instances. So when the nested container is disposed, all object graph is released.
I don't smell anything as long as, like comments suggest, you remove the default parameterless constructor from AccountService. Any decent IoC container should be able to cascade the dependencies, so that when you inject IAccountService into AccountManagementController, it will resolve AccountService's dependency on IUnitOfWork
Most of the J2EE(Spring and JPA) classes are designed with interfaces. Except for inheritance, are there any technical reasons for this? Like dynamic proxy or AOP, I need more technical details about this
ex
public interface UserDAO {
void delete();
void update();
void save();
List<User> get();
}
public class UserDAOImpl implements UserDAO {
public void delete(){}
public void update(){}
public void save(){}
public List<User> get(){}
}
There are 3 main reasons, IMO:
First reason: proxies.
If you ask Spring for the bean of type UserDAO, it will in fact return a proxy encapsulating the actual UserDAOImpl instance. This allows it to demarcate transactions, verify security authorization, log accesses, compute statistics, etc. It's possible to do it without an interface, but then byte-code manipulation is needed.
Second reasons: testability.
When unit-testing a business service which uses a UserDAO, you typically inject a mock UserDAO implementation. Once again, this is easier to do when UserDAO is an interface. It's possible with a concrete class, but it has not always been, and it's still easier with an interface
Third reason: decoupling.
By using an interface, you have a place where you define the real contract of the DAO for its clients. Sure, it needs a setDataSource() method in the concrete implementation, but clients don't care about that. All they need is set of data-access methods offered by the DAO. By separating the interface and the concrete implementation, you make sure that the client doesn't rely on implementation details of the DAO.
Interfaces for one are contracts as I see them . For example , a set of software engineers(Implementation classes) may have a specific contract with a company(Interface) . The company may choose to switch between the engineers from time to time based on the project needs . Since they come under the same contract and follow the same rules , switching is easier than bringing in a resource from outside (writing a new class) every time the project needs change . You just have to change the configurations to switch the implementation classes .
Interfaces are clean and is a one point access to the rules which the classes implement .
Links
spring and interfaces
What does it mean to "program to an interface"?
http://www.artima.com/lejava/articles/designprinciples.html
Because you have mentioned Spring explicite.
Spring AOP can be used in different configurations. The default one uses java dynamic proxies (java.lang.reflect.Proxy). This can be only applied to Interfaces
Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied.
#see Spring Reference Chapter 7.1.3 AOP Proxies
#see Dynamic Proxy Classes