Instanciate Entity Framework context per request via Microsoft Unity in WebApi 2.0 - entity-framework

I have a N-layer solution that works correctly in my dev environment. Apparently it works also on production environment, but sometime the execution fails. I do not understand why. I just know that nothing changes on database, no usefull error is visible and no log is written.
My supposition is a concurrency problem. I think that something fails when I try to do more than one select once the entity framework context has been initialized.
Here how my solution is structured
In the facade I inject the entity framework context. Here the configuration on my web.config of the service interface:
<containers>
<container>
<types>
<register type="it.MC.IContext.IDataContext, IContext"
mapTo="it.MC.EntityFrameworkContext.PublicAreaContext, EntityFrameworkContext">
<lifetime type="singleton" />
</register>
<register type="it.MC.IFacade.IPublicAreaFacade, IFacade"
mapTo="it.MC.Facade.PublicAreaFacade, Facade">
<interceptor type="TransparentProxyInterceptor" />
<lifetime type="singleton" />
<constructor>
<param name="context" type="it.MC.IContext.IDataContext, IContext"/>
</constructor>
</register>
</types>
</container>
</containers>
As you can see, my context and the facade are singleton. I think both are really wrong. I think that both Facade that the entity Framewrk context should be instanciate per request. I think this will solve the problem of the concurrency too.
Can anyone help me to correct my code please?
Thank you

I know that your question is:
Can anyone help me to correct my code please?
I read it like this:
Can anyone help me change this code so that IContext and IFacade will be re-initialized per request.
With that said... Yes, I also doubt that you want to keep your IContext as a singleton.
Why you shouldn't use singleton DataContexts in Entity Framework
Here's how you can change the lifetimemanager to PerRequestLifetimeManager, if that's what you want. Note that you probably need the Unity.Mvc NuGet-package.
<containers>
<container>
<types>
<register type="it.MC.IContext.IDataContext, IContext"
mapTo="it.MC.EntityFrameworkContext.PublicAreaContext, EntityFrameworkContext">
<lifetime type="Microsoft.Practices.Unity.PerRequestLifetimeManager, Microsoft.Practices.Unity.Mvc" />
</register>
<register type="it.MC.IFacade.IPublicAreaFacade, IFacade"
mapTo="it.MC.Facade.PublicAreaFacade, Facade">
<interceptor type="TransparentProxyInterceptor" />
<lifetime type="Microsoft.Practices.Unity.PerRequestLifetimeManager, Microsoft.Practices.Unity.Mvc" />
<constructor>
<param name="context" type="it.MC.IContext.IDataContext, IContext"/>
</constructor>
</register>
</types>
</container>
</containers>
Before moving to production I suggest you read this post about the PerRequestLifetimeManager.
Its purpose would be to only instantiate one instance per request,
which could (for example) prevent redundant operations and lookups
during the course of a single request.
The danger is if someone assumes that the object created is a good
place to store state during the request. The idea of dependency
injection is that a class receives a dependency (commonly an
interface) and doesn't "know" anything about it at all except that it
implements that interface.
Also, think about the Facade you got, and how it will work if it's re-initated every request. Does it perform any heavy operations at initialization? You might want to think about the lifetimemanager for that one.
UPDATE
Since you're using WebAPI you should be able to use HierarchicalLifetimeManager instead.
http://www.asp.net/web-api/overview/advanced/dependency-injection
The dependency resolver attached to the HttpConfiguration object has
global scope. When Web API creates a controller, it calls BeginScope.
This method returns an IDependencyScope that represents a child scope.
Web API then calls GetService on the child scope to create the
controller. When request is complete, Web API calls Dispose on the
child scope. Use the Dispose method to dispose of the controller’s
dependencies.
http://www.devtrends.co.uk/blog/introducing-the-unity.webapi-nuget-package
If you are registering any components that implement IDisposable such
as Entity Framework's DbContext, you will want to make sure that these
components get disposed of at the end of the request. This is achieved
by registering these components with a HierarchicalLifetimeManager.

Related

Use custom annotation in hexMachina

I try to use custom annotation in hexMachina.
In one module, I register my metadata:
this._annotationProvider.registerMetaData("Url", this.urlProviderModel.getUrl)
And in a Command, executed in a Macro :
#Url("applicationConfig")
public var applicationConfigUrl:String;
The Macro is executed in context :
<state id="assemblingEnd" ref="applicationContext.state.ASSEMBLING_END">
<enter command-class="app.adapter.bootstrap.BootstrapMacro" fire-once="true"/>
</state>
applicationConfigUrl has null
What is missing?
AnnotationProvider delivers data based on domain references.
In the previous example, metadata is registered on module's domain, and the BootstrapMacro instance is executed from the main application context's domain (its parent).
To fix the problem, I have registered the annotation to TopLevelDomain with :
AnnotationProvider.getAnnotationProvider().registerMetaData("Url", urlProviderModule.getUrlFunction());
With this kind of registration, the annotation will be available to every domain. This is because AnnotationProvider API provides automatic inheritance for every registration to all children domains, with cascading effect as well (children of children...).
Just a quick addition, it's also possible to register from your main context without targeting the top-level domain.
AnnotationProvider.getAnnotationProvider( context.getDomain() ).registerMetaData("Url", urlProviderModule.getUrlFunction());
The unit tests can help to understand the behaviors. They are available here.

Entity Framework 5 built in Database Initializers and Seed method in Code First

I'm using EF 5 and trying to figure out how different built in database initializers are calling the Seed() method.
These are my questions:
1. What is a good initializer for seeding the database only when the model changes?
2. How to configure each db initializer in web.config?
Clarifications for my first question:
So far I know that these are the built in database initializers of EF 5:
MigrateDatabaseToLatestVersion
CreateDatabaseIfNotExists
DropCreateDatabaseIfModelChanges
DropCreateDatabaseAlways
My problem is in understanding when the Seed method of each of these initializers is called. I've looked inside the EntityFramework dll and checked the code of each of these initializer's InitializeDatabase() method to check when each is called. This is what I found:
MigrateDatabaseToLatestVersion: I couldn't find out when the seed method is called but from my tests it is called every time the app runs, no matter if there are changes in the model.
CreateDatabaseIfNotExists: I could find that the Seed method is called only when creating the database. If it exists, no seed should be done.
DropCreateDatabaseIfModelChanges: It seems that InitializeDatabase method calls Seed() every time, no matter if the model changed or not. The call is outside the if(context.Dabase.Exists()) check.
DropCreateDatabaseAlways: It is obvious that this will always call Seed method.
Is this correct? If so, it doesn't seem like I could restrict seeding to the case in which the model changes and I should probably write a custom initializer.
Regarding my 2nd question, I know how to configure the MigrateDatabaseToLatestVersion but i find it difficult to write as I don't know the meaning of this declaration (especially the '2 part - is it the value of an enum, in which case how should I figure what is the corresponding number of other initializers?):
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<contexts>
<context type="Digidata.MP.Data.ObjectContext, Digidata.MP.Data">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Digidata.MP.Data.ObjectContext, Digidata.MP.Data], [Digidata.MP.Data.Migrations.Configuration, Digidata.MP.Data]], EntityFramework"/>
</context>
</contexts>
Where can I find an explanation of how to declare the built in initializers in a config file?

Does Autofac allow specifying what dependency type should be injected into constructor

Lets say I have EmailService which implments IEmailService. And EmailService has constructor dependency on ILoggingService. Now given that I have several implementations of ILoggingService, can achieve something like this:
<component service="IEmailService, MyInterfaces" type="EmailService, MyLib">
<parameters>
<parameter name="loggingService" value="LoggingService, MyLib" />
</parameters>
</component>
I have looked at giving names to registered types but so far couldn't find an example of how to use them from XML configuration.
In short I want to use XML configuration to specify which concrete logger implementation gets injection.
XML configuration in Autofac is targeted more toward the 80% use case rather than being a full implementation of Autofac's flexibility in XML form. Autofac instead recommends using its module mechanism for configuration. Modules, coupled with the XML configuration, can be a very powerful way to achieve what you're looking to accomplish and still have that flexibility to switch between dependencies as needed.
First, create an Autofac module that does the registration you want:
public class EmailModule
{
protected override void Load(ContainerBuilder builder)
{
// Register a named logging service so we can locate
// this specific one later.
builder.RegisterType<LoggingService>()
.Named<ILoggingService>("emailLogger");
// Create a ResolvedParameter we can use to force resolution
// of the constructor parameter to the named logger type.
var loggingServiceParameter = new ResolvedParameter(
(pi, ctx) => pi.Name == "loggingService",
(pi, ctx) => ctx.ResolveNamed<ILoggingService>("emailLogger"));
// Add the ResolvedParameter to the type registration so it
// knows to use it when resolving.
builder.RegisterType<EmailService>()
.As<IEmailService>()
.WithParameter(loggingServiceParameter);
}
}
Notice it's a little more complex of a registration because you're requiring a very specific resolution.
Now in XML configuration, register that module:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section
name="autofac"
type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
</configSections>
<autofac>
<modules>
<module type="EmailModule, MyAssembly" />
</modules>
</autofac>
</configuration>
When you want to switch configurations, register a different module rather than fiddling with specific component registries.
Code disclaimer: I'm writing the syntax from memory and I'm not a compiler, so you may have to do a little tweaking... but the premise holds. Isolate the complexity in a module, then register your module.

Explain RestEasy providers, resources and singletons in relation to classes vs instances?

I'm building a JAX-RS app that consists of a stockroom and a workplace. The stockroom holds a set of Java classes that can be instantiated (via AJAX) to create named instances of those classes in the workplace.
So far I'm able to reference the stockroom and workplace fine by declaring them as "singletons" in the RestEasy application
singletons.add(StockPlace.getInstance());
singletons.add(WorkPlace.getInstance());
I'm unable to understand how to understand how the stockroom content classes should be handled. The effect I'm trying to achieve is that when I dynamically create an instance of one of the stockroom classes, that instance can be dynamically accessed via REST commands. I've tried various permutations of:
classes.add(SomeComponent.class);
I think I'm missing knowledge of how the Java notion of how classes work as factories for making instances, and how both of these relate to what RestEasy calls classes, singletons (singletons ARE classes, yet RestEasy registers them as instances) and resources (instances?).
I suspect I'll wind up needing to dynamically register new instances but can't find a way to do that either. I did find a way to do it given the ServletContext, but am not able to get access to that either. Can someone get me on the right track?
Our eventual answer to this question was to bail out of RestEasy and convert to DropWizard. That problem and many others vanished and everything became easy again.
I believe I know what you are after, but I should at least give you a push in the right direction.
You will need to add the annotated RESTEasy class(es) to the registry. Below is the class I used for a recent project. It adds to the singletons (per what you did) but it also adds to the registry.
public class RESTEasyServerApplication extends javax.ws.rs.core.Application
{
// The RESTEasy registry
#Autowired
protected org.jboss.resteasy.spi.Registry registry;
// The annotated RESTEasy handler classes
private Set<Object> singletons = new HashSet<Object>();
private List<Object> handlers = new ArrayList<Object>();
public RESTEasyServerApplication()
{}
#Override
public Set<Object> getSingletons()
{
return singletons;
}
// Spring injection support
public void setHandlers( List<Object> handlers )
{
for( Object handler : handlers )
{
if( registry != null )
{
// Save a reference to the handler
this.handlers.add( handler );
// Register the handler with RESTEasy
registry.addSingletonResource( handler );
}
singletons.add( handler );
}
}
// Spring injection support
public List<Object> getHandlers()
{
return handlers;
}
}
I used Spring, and here is the relevant configuration:
<!-- RESTeasy/Spring integration -->
<import resource="classpath:springmvc-resteasy.xml" />
<!-- RESTeasy server application -->
<bean id="application" class="blah.blah.resteasy.RESTEasyServerApplication">
<property name="handlers">
<list>
<!-- Application specific handler classes -->
<ref bean="sample"/>
</list>
</property>
</bean>
Should be easy to modify/add a method to accept a single annotated RESTEasy class and make it work dynamically as required. The registry is defined in the springmvc-resteasy.xml file.
Since I've found no answers that don't involve strapping another whole layer of complexity (Spring) onto RestEasy, the solution I found livable is outlined in the final comment above. That is, don't rely on sending remote messages to instances unless the app is truly stateless (e.g. instances don't persist across messages). Only send remote messages to singletons which do persist across requests. Each such message can identify the desired instance (by String id in my case), and the singleton can forward to the identified instance as an ordinary POJO.
I still don't see why RestEasy unconditionally treats non-Singletons (instances) as ephemeral. Statelessness is not a restriction on REST, only a restriction on when GET methods can be used (idempotent calls). PUT and POST calls are neither stateless nor idempotent.
As I understand this, of course, and feel free to correct me. My focus is getting this app on the air, not exploring every corner of RestEasy, REST, and certainly not Spring.

NoSQL with ColdFusion, Bean+Service+DAO & OOP or good old Array/Struct & Procedural?

How do you architect the CF backend model w/ NoSQL that are simple, flexible, efficient and clean?
Since NoSQL doc has no fixed schema like SQL row, it doesn't really fit well with Objects which are rather static. Therefore the typical Bean+DAO+Service OOP architecture doesn't seem to fit well.
I'm thinking of using plain old Struct's, but then I cannot add behavior onto it and it's going to make the whole project very procedural, which may not be a bad thing?
However, if I just use plain old struct, the DB implementations is leaked everywhere including the View layer...
Or... shall I translate the array's into CF's Query object for the View layer?
Comment? Idea? Suggestion?
Thanks!
I've written a couple applications in CF that use NoSQL datastores - one uses the Google App Engine datastore, and another with MongoDB.
In both cases, I made CFCs to act as my objects. But, I used a homegrown object "framework" that uses onMissingMethod for accessors, and cfproperty with lots of custom metadata to define properties of the objects.
For instance, this is all I NEED to define for a model, unless it has custom business logic:
<cfcomponent output="false" persistentLayer="GAE" persistentClass="asana" extends="com.bespokelogic.framework.BaseModel">
<cfproperty name="id" type="string" persistentDatatype="string" settable="true" gettable="true" required="true">
<cfproperty name="deckSet" type="string" persistentDatatype="string" settable="true" gettable="true" default="basic">
<cfproperty name="englishName" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="traditionalName" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="pronunciation" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="anatomicalFocus" type="array" persistentDatatype="array" settable="true" gettable="true" default="#arrayNew(1)#">
<cfproperty name="therapeuticFocus" type="array" persistentDatatype="array" settable="true" gettable="true" default="#arrayNew(1)#">
<cfproperty name="benefits" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="variations" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="contraindications" type="array" persistentDatatype="array" settable="true" gettable="true" default="#arrayNew(1)#">
<cfproperty name="skill" type="string" persistentDatatype="string" settable="true" gettable="true">
<cfproperty name="instructions" type="string" persistentDatatype="string" settable="true" gettable="true">
</cfcomponent>
The CFCs all extend a base model which has validate, serialize, deserialize, and virtual getter/setter methods.
Then, I have a persistence layer that knows how to get and put objects from/into the datastore.
I would then write a service for each of the models which utilize the persistence layer.
The upshot is that the models know how to serialize their property data, and the persistencelayer knows how to put that into the datastore.
So, in a sense, its not an object-relational manager, but more of an object-document manager.
The framework's a lot more full featured in reality, as my design was that I take some models, and persist them in SQL, some in NoSQL, all in the same application - and I could swap out the underlying datastore with no recoding of the app. It was a partial success.
In your case, if you're using a single datastore, you can skip all that complicated stuff.
You just need a base object which knows how to serialize and deserialize models, and you getter/setter stuff. Decide how you want to store property data in the CFC. I used a struct called "variables.instance._properties{}"
Then write a service for your model(s) that has "put" and "fetch" methods. The "put" method, for instance, takes a model, calls the "serialize" method on it to turn it into JSON, then stuffs it into Mongo. The "fetch" method gets the Mongo record, creates a new instance of the CFC, and passes the Mongo record to the deserialize method.
That was pretty rambling...
TL;DR: "Objects in CF (such as they are) are not really all that static. Use CFCs. Use onMissingMethod to allow dynamic properties. Store properties in a way that allows you to serialize and deserialize them into a format (usually JSON) that is easily digestible by your datastore. Write a simple persistence layer that gets and puts documents to/from the datastore. Write simple services which implement your persistence layer and take and return you dynamic models.
CF's pretty well suited for NoSQL in my opinion.
I've settled with Proxy object (that has an embed 'instance' struct). The DAO layer just use getMemento() & setMemento()
I also used an Iterator object for iterating through an array of results.