Injecting Correct ISessionFactory Into IRepository Using Castle Windsor and NHibernate Facility - nhibernate

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.

Related

autofac dependancy injection throwing an exception

In my web config I have
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
</configSections>
and then...
<autofac>
<components>
<component type="xyz.Service.TrainerService, xyz.Service" service="xyz.Service.Contracts.ITrainerService,xyz.Service.Contracts">/component>
</components>
</autofac>
inside my WebApiConfig.cs I have the following 2 lines included...
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
var container = builder.Build();
TrainerService is the concreate class and ITrainerService is the relevant interface while xyz.Service and xyz.Service.Contracts are namespaces.
But the above code gives me the "The type 'xyz.Service.TrainerService, xyz.Service' could not be found. It may require assembly qualification, e.g. "MyType, MyAssembly" error on following line
var container = builder.Build();
Can some one please give me a solution to this in order to get autofac dependancy injection working?

MVC 5 NHibernate Autofac, not able to see database data

I'm building an MVC5 web app connecting to a MS SQL 2008 database, so that the users can search and make changes to data stored there. I've looked at a bunch of autofac tutorials and examples, but can't seem to make any of them work.
I'm assuming my autofac configuration is the problem, because when I run the app it says my model is null. Which I think means the autofac is not connecting to the datbase.
So, in my global.asax.cs file I have the following:
protected void Application_Start()
{
#region Autofac
// Register Controllers
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly); //all controllers in assembly at once ?
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();
// Set the Dependency Resolver
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Register Model Binders
builder.RegisterModelBinders(typeof(MvcApplication).Assembly); //all binders in assembly at once ?
builder.RegisterModelBinderProvider();
// Register Modules
builder.RegisterModule<PersistenceModule>();
#endregion
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I have a hibernate.cfg.xml file as
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=DEVSRV\SQLSERVER;Initial Catalog=tipdemo;Persist Security Info=True;User ID=admin;Password=***********</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<!--<mapping assembly="NHibernateTest"/> -->
</session-factory>
</hibernate-configuration>
</configuration>
And my PersistenceModule class is:
public class PersistenceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
if (builder == null)
throw new ArgumentException("builder", "builder is null");
base.Load(builder);
}
private ISessionFactory ConfigureDB()
{
Configuration cfg = new Configuration().Configure(System.Web.HttpContext.Current.Server.MapPath("~/Config/hibernate.cfg.xml"));
cfg.AddAssembly(typeof(Domain.General.Project).Assembly);
return cfg.BuildSessionFactory();
}
}
You can't register things in the container after it's built.
On line 11 in the sample for Application_Start you're building the container, but then after you set the DependencyResolver you're registering more stuff with the ContainerBuilder. You can't do that - you have to register everything first, then build the container as the last thing you do.
That's why it's never entering your PersistenceModule - you've already built the container, so it's not actually getting registered.
If, for some reason, you need to add registrations to an already-built container, you need to create an all new ContainerBuilder and call builder.Update(container). However, I strongly recommend you just reorder things so the container is built last rather than go the Update route if possible.

Logging SQL statements of Entity Framework 5 for database-first aproach

I'm trying to use Entity Framework Tracing Provider to log the SQL staments generated.
I changed my context class to something like this:
public partial class MyDBContext: DbContext
{
public MyDBContext(string nameOrConnectionString)
: base(EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString), true)
{
// enable sql tracing
((IObjectContextAdapter) this).ObjectContext.EnableTracing();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
//DbSets definition....
}
But this doesn't log the SQL statements on the Output window...
Should I had something more in the class or in web.config file? (I'm working on a ASP.NET MVC 4 project)
I using the solution in the following post:Entity Framework 4.1 - EFTracingProvider
but I made some changes that I don't know if they are important:
The class is partial instead of abstract, and the constructor is public instead of protected...
What am I missing?
After modifying your code, you need to enable tracing in your web.config like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<sources>
<source name="EntityFramework.NorthwindEntities" switchValue="All" />
</sources>
</system.diagnostics>
</configuration>
The name of your TraceSource should be your context name prefixed with 'EntityFramework'.
Make sure that you disable tracing when you deploy your application to production by setting the switchValue to Off.

Why is my WCF Data Services method not appearing in the OData collections list?

When I view the root of my WCF Data Services service (http://localhost/MyService.svc/) in a browser I see this:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<service xml:base="http://localhost/MyService.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">
<workspace>
<atom:title>Default</atom:title>
</workspace>
</service>
I would expect to see a list of collections.
When I go to the $metadata URL I see this:
<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="1.0">
<Schema Namespace="MyApp" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/05/edm">
<ComplexType Name="Package">
<Property Name="Id" Type="Edm.String" Nullable="true" />
</ComplexType>
</Schema>
<Schema Namespace="MyApp" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/05/edm">
<EntityContainer Name="PackageService" m:IsDefaultEntityContainer="true">
<FunctionImport Name="GetQueryablePackages" ReturnType="Collection(MyApp.Package)" m:HttpMethod="GET" />
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
Why might my GetQueryablePackages collection not be appearing?
I'm using these access settings:
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
Service operations (the function import in the EDM) is not exposed in the service document. Only entity sets are exposed there.
If you want your data to be exposed in the service document make an entity set out of it. Depending on the provider model this differs. Typically it means exposing a property of type IQueryable on your context class. Note that T has to be an entity type (must have a key).
Can you share the context definition where you have defined the IQueryable <> properties. There are 2 things that come to my mind: First the properties must be of type IQueryable<> or some type that derives from it. Second, the element type refered by the IQueryable<> must be an entity type i.e. they must have key properties declared in them.
Hope this helps.
Thanks
Pratik
Or you can create an extension method like this:
public static class TestEntitiesExtensions
{
public static IEnumerable<Package> GetQueryablePackages(this TestEntities context)
{
var uri = new Uri(context.BaseUri, "GetQueryablePackages");
return context.Execute<Package>(uri);
}
}

WCF: Configuring Known Types

I want to know as to how to configure known types in WCF. For example, I have a Person class and an Employee class. The Employee class is a sublass of the Person class. Both class are marked with a [DataContract] attribute.
I dont want to hardcode the known type of a class, like putting a [ServiceKnownType(typeof(Employee))] at the Person class so that WCF will know that Employee is a subclass of Person.
Now, I added to the host's App.config the following XML configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="Person, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral,PublicKeyToken=null">
<knownType type="Employee, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral, PublicKeyToken=null" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
<system.serviceModel>
.......
</system.serviceModel>
</configuration>
I compiled it, run the host, added a service reference at the client and added some code and run the client. But an error occured:
The formatter threw an exception while
trying to deserialize the message:
There was an error while trying to
deserialize parameter
http://www.herbertsabanal.net:person.
The InnerException message was 'Error
in line 1 position 247. Element
'http://www.herbertsabanal.net:person'
contains data of the
'http://www.herbertsabanal.net/Data:Employee'
data contract. The deserializer has no
knowledge of any type that maps to
this contract. Add the type
corresponding to 'Employee' to the
list of known types - for example, by
using the KnownTypeAttribute attribute
or by adding it to the list of known
types passed to
DataContractSerializer.'. Please see
InnerException for more details.
Below are the data contracts:
[DataContract(Namespace="http://www.herbertsabanal.net/Data", Name="Person")]
class Person
{
string _name;
int _age;
[DataMember(Name="Name", Order=0)]
public string Name
{
get { return _name; }
set { _name = value; }
}
[DataMember(Name="Age", Order=1)]
public int Age
{
get { return _age; }
set { _age = value; }
}
}
[DataContract(Namespace="http://www.herbertsabanal.net/Data", Name="Employee")]
class Employee : Person
{
string _id;
[DataMember]
public string ID
{
get { return _id; }
set { _id = value; }
}
}
Btw, I didn't use class libraries (WCF class libraries or non-WCF class libraries) for my service. I just plain coded it in the host project.
I guess there must be a problem at the config file (please see config file above). Or I must be missing something. Any help would be pretty much appreciated.
I guess I have found the answer now.
The configuration file I posted above looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="Person, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral,PublicKeyToken=null">
<knownType type="Employee, WCFWithNoLibrary, Version=1.0.0.0,Culture=neutral, PublicKeyToken=null" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
<system.serviceModel>
.......
</system.serviceModel>
</configuration>
What I just added was, the Namespace of the Person class and the Employee class. And no need for the longer Version and Culture values.... The correct configuration should be:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="WCFWithNoLibrary.Person, WCFWithNoLibrary">
<knownType type="WCFWithNoLibrary.Employee, WCFWithNoLibrary" />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
<system.serviceModel>
.......
</system.serviceModel>
</configuration>
Now it is shorter and makes more sense. But if 3rd party libraries are used, then adding version, culture, publickeytokens would be required.
I know this was answered a long time ago, but, another (maybe more obvious for future programmers) solution:
[KnownType(typeof(SubClass))]
public class BaseClass
Scott
I got this lengthy error message also in another case. I did use the KnownTypeAttribute and had successfully deployed an application which uses WCF.RIA to production. In the second release I added a new subtype, and added the necessary corresponding KnownTypeAttribute (the compiler did not accept it without this attribute - great). What the compiler did accept and what ran on my machine, did not run in production, however. Only in production I got the error mentioned above. Comparing all the uses of the existing subtypes and the new one revealed I had forgotten that WCF.RIA requires the name of the subtype to be used in a name of a method, like GetMySubTypes. So if you get this error after having added the attributes, see whether it's because of WCF.RIAs conventions.