How to use the Ninject xml config with TEntity? - ninject

This should work:-
Bind(typeof(IRepository<>)).To(typeof(Repository<>));
where:-
IRepository<> is an interface of the form:-
public interface IRepository<T> where T :class
{
//...
}
Repository<> is a class of the form:-
public class Repository<T>:IRepository<T> where T :class
{
//...
}
But how to do it in XML configuration using Ninject.Extensions.Xml?
It does not work.

You can find out what the name of the type is by doing typeof(IRepository<>).FullName and then configure the XML as follows:
<module name="myXmlConfigurationModule">
<bind service="MyNamespace.IRepository`1, MyAssembly"
to="MyNamespace.Repository`1, MyAssembly" />
</module>
I haven't used the XML extensions for Ninject before, but that should work

Related

Entlib Custom exception handler missing mappings

I implemented custom exception handler which works, except mappings from xml configuration policy. Those mapping works with standard Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler
My implementation
[ConfigurationElementType(typeof(CustomHandlerData))]
public class IdentityFaultContractExceptionHandler : IExceptionHandler
{
public IdentityFaultContractExceptionHandler(NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, string exceptionMessage, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(IStringResolver exceptionMessageResolver, Type faultContractType, NameValueCollection attributes)
{
}
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
return new Exception();
}
and part of the configuration
<add name="All Exceptions" type="System.Exception, mscorlib" postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add type="MyClass.IdentityFaultContractExceptionHandler, MyClass" exceptionMessage="An error occurred in the service." faultContractType="MyClass.UnexpectedServerFault, MyClass" name="Fault Contract Exception Handler" >
<mappings>
<add source="{Message}" name="Message" />
</mappings>
</add>
</exceptionHandlers>
</add>
When I remove mappping node service works, when I add, then I got error : unrecognize element mappings.
If you are using a CustomHandlerData attribute then your configuration needs to use XML Attributes which then get passed in as a NameValueCollection to the custom handler constructor. If you want to have custom XML then you will have to use Full Design-time Integration. If you want to go down that road then you should look at the FaultContractExceptionHandlerData source code since your code would probably be quite similar.

Optional Resources in Spring.Net

How to include Spring configuration files optionally? I think about something simular to this:
<spring>
<context>
<resource uri="file:///Objects/RequiredObjects.xml" />
<resource uri="file:///Objects/OptionalObjects.xml" required="false" />
</context>
This way I could provide developers the possibility to override some configuration parts (e.g. for a local speed improvement or automatism during app startup) without affecting the app.config and the problem that a developer could checkin his modified file when it is not really his intent to change the config for all.
Not as simple as in AutoFac (because there is already a builtin way) but possible to achieve something similar with a little coding:
using System.IO;
using System.Xml;
using Spring.Core.IO;
public class OptionalFileSystemResource : FileSystemResource
{
public OptionalFileSystemResource(string uri)
: base(uri)
{
}
public override Stream InputStream
{
get
{
if (System.IO.File.Exists(this.Uri.LocalPath))
{
return base.InputStream;
}
return CreateEmptyStream();
}
}
private static Stream CreateEmptyStream()
{
var xml = new XmlDocument();
xml.LoadXml("<objects />");
var stream = new MemoryStream();
xml.Save(stream);
stream.Position = 0;
return stream;
}
}
Register a section handler:
<sectionGroup name="spring">
...
<section name="resourceHandlers" type="Spring.Context.Support.ResourceHandlersSectionHandler, Spring.Core"/>
...
</sectionGroup>
...
<spring>
<resourceHandlers>
<handler protocol="optionalfile" type="MyCoolStuff.OptionalFileSystemResource, MyCoolStuff" />
</resourceHandlers>
...
<context>
<resource uri="file://Config/MyMandatoryFile.xml" />
<resource uri="optionalfile://Config/MyOptionalFile.xml" />
...
You'll find more information about resources and resource handlers in the Spring.Net documentation.

EJB #PersistenceContext EntityManager Throws NullPointerException

I'm having a problem with injecting EntityManager by using #PersistenceContext. I try to inject EntityManager in EJB class with #PersistenceContext and I always get NullPointerException.
Here is EJB class:
#Stateless
public class BookEJB {
public BookEJB(){
}
#PersistenceContext(unitName = "BookWebStorePU")
private EntityManager em;
public Book createBook(Book book) throws Exception {
System.out.println("EM: " + em);
em.persist(book);
return book;
}
public Book findBookByIsbn10(String isbn10){
Book book = new Book();
em.find(Book.class, isbn10);
return book;
}
//Other methods here
}
Here's Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="BookWebStorePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/BookWebStoreDB"/>
<property name="javax.persistence.jdbc.user" value="bookwebstoreadmin"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<!-- Let EclipseLink create database schemas automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
</properties>
Here's my test file:
public class BookDaoTests {
private BookEJB bookDao;
private Book newBook;
#Before
public void init() {
newBook = new Book();
newBook.setName("Flying Cow");
newBook.setDescription("Super cool story about flying cow");
newBook.setAuthor("Me");
newBook.setIsbn10("0123456789");
newBook.setIllustrations(true);
newBook.setPublishYear(2013);
newBook.setNumberOfPages(1567);
newBook.setQuantity(58);
bookDao = new BookEJB();
}
#Test
public void createBook() throws Exception{
bookDao.createBook(newBook);
Assert.assertEquals("Book was created!", bookDao.findBookByIsbn10("0123456789"), newBook);
}
}
So when I run that test file I get following error:
Testcase: createBook(com.mysite.bookstore.tests.BookDaoTests): Caused an ERROR
null
java.lang.NullPointerException
at com.mysite.bookwebstore.beans.BookEJB.createBook(BookEJB.java:27)
at com.mysite.bookstore.tests.BookDaoTests.createBook(BookDaoTests.java:46)
EM: null
I use following technologies:
Glassfish 4
JavaEE 7
JSF
EclipseLink 2.1
Java DB
I hope we can find some solution for this problem. I have been tackling now 3 days of this problem and searched and tested solutions from Google and from Stackoverflow but none of the solutions helped/worked. To make sure that the EntityManager was really null, I debugged test file and saw that indeed it gives null. So how can I solve this problem?
The EntityManager instance, is injected when the EJB is deployed in the Container.
If you take a look at the lifecycle of enterprise bean, you will see clearly when dependency injection occurs.
When the Container sees the #Persistencecontext annotation it will inject a container-managed EntityManager.
The problem is that the code executed in this test is not managed by the Container, therefore, no one inject the necessary dependencies.
bookDao = new BookEJB();
When you run the test, the BookEJB class is just a simple POJO, the #Stateless and #PersistenceContext annotations are simply ignored.
You have several alternatives in order to test your EJB, take a look at this link.

Injecting Correct ISessionFactory Into IRepository Using Castle Windsor and NHibernate Facility

I have three SQL Server databases that a single application retrieves data from. I am using NHibernate to retrieve data from the different databases. I have things set up so that each database has its own repository and class mappings in its own assembly. In my castle.config file I have the database connections setup using the Castle NHibernate Facility:
<?xml version="1.0" encoding="utf-8" ?>
<castle>
<facilities>
<facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Windsor" />
<facility id="nhibernate" isWeb="false" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration">
<factory id="databaseone.factory" alias="databaseone">
<settings>
<!--Settings Here -->
</settings>
<assemblies>
<assembly>DAL.DatabaseOne</assembly>
</assemblies>
</factory>
<factory id="databasetwo.factory" alias="databasetwo">
<settings>
<!--Settings Here -->
</settings>
<assemblies>
<assembly>DAL.DatabaseTwo</assembly>
</assemblies>
</factory>
<factory id="databasethree.factory" alias="databasethree">
<settings>
<!--Settings Here -->
</settings>
<assemblies>
<assembly>DAL.DatabaseThree</assembly>
</assemblies>
</factory>
</facility>
</facilities>
</castle>
All of my repositories have a constructor that take an ISessionFactory as the parameter:
public MyRepository<T> : IRepository<T>
{
public MyRepository(ISessionFactory factory)
{
//Do stuff here
}
}
I have an installer class where I would like to define the various repositories:
//In install method of IWindsorInstaller
container.register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(MyRepository<>));
Using one database things work fine. When I add the second database to the mix, the same ISessionFactory is injected into all of the repositories. My question is what is the best way to handle this? I could manually specify which ISessionFactory should be injected into which Repository<> but I cannot seem to find documentation on this. The best way would be if I could say something like: For all class mappings in assembly DAL.DatabaseOne, always inject the ISessionFactory corresponding to databaseone.factory; and for all class mappings in assembly DAL.DatabaseTwo, always inject the ISessionFactory corresponding to databasetwo.factory.
Thoughts or suggestions?
This is explained in this post by Fabio Maulo toward the end under the heading 'Configuring your DAOs/Repository for multiple DB'.
He maps the factory individually for each domain class but you could also use reflection on each of the domain assemblies in your case to register the appropriate factory.

How to map composite-id with fluent nhibernate using an interface?

I'm trying to switch out .hbm mappings to fluent mappings and have a problem with the mapping of composite-ids and the usage of Interfaces
the Class looks as follows:
public class ClassWithCompositeId {
public virtual IKeyOne KeyOne { get; set; }
public virtual IKeyTwo KeyTwo { get; set; }
}
our hbm mapping looks like this:
<hibernate-mapping ...>
<class name="ClassWithCompositeId" table="t_classwithcompositeid">
<composite-id>
<key-many-to-one name="KeyOne" column="colkeyone" class="company.namespace.boSkillBase, BL_Stammdaten" />
<key-many-to-one name="KeyTwo" column="colkeytwo" class="boQualifikation" />
</composite-id>
</hibernate-mapping>
Please note, that we got interfaces in the Class! No I'm trying to map this with Fluent nhibernate.
Map {
public ClassWithCompositeIdMap() {
CompositeId()
.KeyReference(x => x.KeyOne, "colkeyone")
.KeyReference(x => x.KeyTwo, "colkeytwo");
...
}
}
But now Fluent generates the Mapping as follows:
...
<composite-id mapped="false" unsaved-value="undefined">
<key-many-to-one name="KeyOne" class="company.namespace.IKeyOne, Interfaces, Version=0.1.4.3379, Culture=neutral, PublicKeyToken=null">
<column name="colkeyone" />
</key-many-to-one>
<key-many-to-one name="KeyTwo" class="company.namespace.IKeyTwo, Interfaces, Version=0.1.4.3379, Culture=neutral, PublicKeyToken=null">
<column name="colkeytwo" />
</key-many-to-one>
</composite-id>
...
The "Class" Attribute points now to the Interface not to the implementation of this interface which results in an error.
How can I tell Fluent nHibernate to use another class as the attribute value?
Try downloading NhGen from SourceForge. It reads database schemas and generates Fluent mappings and classes etc. While all the code might not be what you need, it should start you off in the right direction as it supports composite keys and represents them as separate classes off the main entity.
I beleive it uses a syntax similar to
CompositeId()
.ComponentCompositeIdentifier(x => x.Key, "Namespace.Key, Assembly")
.KeyProperty(x => x.Key.Id1, "Id1")
.KeyProperty(x => x.Key.Id2, "Id2")
.KeyProperty(x => x.Key.Id3, "Id3");
Tanks! But I've found the answer on my on. In fact i found a missing feature in fluent nHibernate. The feature has already been added to the dev branch by Paul Batum.
You would use it like so:
Map {
public ClassWithCompositeIdMap() {
CompositeId()
.KeyReference(x => x.KeyOne, k =>
k.Type<KeyOneImplementation>(), "colkeyone")
.KeyReference(x => x.KeyTwo, k =>
k.Type<KeyTwoImplementation>(), "colkeytwo");
...
}
}
http://github.com/paulbatum/fluent-nhibernate/tree/dev
You can see the original Conversation here: http://support.fluentnhibernate.org/discussions/help/349-how-to-map-a-composite-id-when-using-interfaces-or-how-to-change-the-class-attribute-in-the-key-many-to-one-tag