Sharing Entity Framework models with other projects using MEF - vb.net

I am currently developing a Windows service and I am am looking to use MEF to compose all of the services components at run time. The data access module (project) is using Entity Framework 4.1 and a Domain Service Class to perform CRUD operations on the entity model.
The problem I have is how to share the models outside the DAL project when composing the DAL into the worker class in the main project.
For exmaple this is one of the methods in the DAL contract interface
Function GetInspectionFaults() As IQueryable(Of InspectionFault)
This interface is currently in the DAL project (not the shared/referenced project containing the other contract interfaces) as it needs references to the entity model for the POCO types.
How do I shared these POCO types?
Phil

Although it might be a bit more work, you might want to consider having a separate set of models (view models if you will) that you have in a shared assembly (maybe a common/contracts assembly). This would enable your parts to utilise a common set of types which are not explicitly dependent on your DAL.
In regards to separation of concerns, I wouldn't recommend exporting your DAL directly, but provide an abstraction to it via something like the Repository pattern. A repository will handle the communication with the DAL and mapping from your domain to your view models.
You can export and import your repository wherever you need it, which means your parts are not dependent on a specific data source. This makes your code more robust, and more testable.

Related

Asp.Net Multi-Tier Architecture Class Library References

I'm a PHP programmer that has applied for an ASP.NET job. They gave me an assignament to make an application (of my choice) that implements a multi-tier arhitecuture.
I have alot of dillemas. As I understand, multi-tier is a concept that doesn't have a universal form and everyone should decide what is best for them. However, they advised me that the presentation layer should not have any refferences to the data access layer, which makes sense. But...
I created a new project with Add new project (that has controllers and views) who is a presentation layer. Now, in the presentation layer, there is also a class library that uses Ninject to inject dependencies for the entire application called NinjectIoC. NinjectIoC has to have a refference to the presentation layer project in order to inject dependencies directly in the controller as an argument. It also has to have refferences to all the other layers (DataAcessLayer, BusinessLayer etc...) order to bind them to their dependencies.
The main problem is that presentation layer project has to also have a refference to the NinjectIoC to create the StandardKernel inside Global.asax which creates a cirucullar dependency and is not permitted.
The only solution is to add a refference to the presentation layer project of all the layers (including DataAccessLayer) which, as I understand, is a bad thing. But, that is the only way to bind all the interfaces of all the layers and execute it inside Global.asax.
Am I thinking wrong?
EDIT:
NinjectIoC has Ninject installed and has a refernce to all the layers in order to bind them across the application. It has to have a reference to the UI in order to be called in Global.asax
UI has to have a reference to NinjectIoC so it can call it in Global.asax for controller binding.
I tried to create an intermediary class library that has a reference to NinjectIoC. That library is referenced in the UI. The problem is that that also creates a circular dependency beacuse NinjectIoC has to have a reference of the UI in order to bind the controllers.
Multi-tier can simply mean that there is a DAL, a BL, and a UI Layer. And the requirement to "not reference the DAL in the UI Layer" can simply mean that your UI layer (MVC4 app) can only reference the BL. This is simple to achieve, for example like this:
An UI Project (MVC4)
An Entities project (Class Library): define here the entities used, and reference it from all the necessary layers (this helps avoiding circular references)
A BL project (Class Library): this must reference the Entities, and the DAL project
A DAL project (Class Library): this references the Entities project
This is the classical, most simple, multi-layered project.
In the final compilation, of course, the indirect dependencies will include the UI project and the 3 libraries, but you don't need to add a reference to the DAL in the UI.
Another different question is using the IoC pattern. In this case, to solve the circular references problem, I recommend you to define separately projects of "Interfaces" and projects of "Implementations" for each layer. Something similar to the previous structurem, but with this changes:
An UI Project
An Entities project
A BL Interfaces project
A project that implements the BL interfaces
A DAL Interfaces project
A project that implements the DAL Interfaces
You need to define which is the main project. It's usually the UI project. This project is the one that will have all the dependencies.
In this case, the UI project depends directly on the BL Interfaces project. And the BL Interfaces will depend on the DAL Interfaces. In a few words, your UI project will only have direct dependencies with the BL Interfaces.
The question is that, when you try to run the code, it will need to solve this dependencies, i.e. find the implementation of the interfaces, and there dependencies. This is the "compositio root" of your application, and it's where you need to register the dependencies. I.e, this is the place where you need to define which concrete implementation will be use for each interface. And, if this implementation depends on other interfaces, you have also to define their implementations. Depending on the framework (I don't know if you can do it with NInject) you can do this dynamically, without the need to add references to the implementation projects. However, even if you have to include references to all the other implementation and interfaces projects you'll have not circular dependencies, and your UI will have not dependencies on the DAL or implementation layers. You only need them for registering them in the IoC Container, which is a very different question. (If you use constructor injection, you get the maximum possible decopuling using this project structure).
Keeping one or several separated entities projects allows you to avoid circular references, and direct dependencies between project. For example, if you defined the entities in your DAL project, nad you use them in your UI project you'd need to add a reference to the DAL project. This problem dissapears if the entities are declared in a separate project.
The pure IoC, like the "Onion Architecture" goes far beyond this by defining the entities and necessary interfaces of dependencies in the main project (UI project), then implementing these dependencies in other projects, and solve them dynamically, to avoid circular references. I.e. all the other projects depend directly or indirectly on the UI project, and not the other way round. In this case you need to solve the dependencies dynamically to avoid the circular references.
As you can see there are many options, and I've shown you several examples of working solutions.

Where to store Interfaces in a Decoupled Architecture in my C# Solution?

I know this question might seem to be answered before, but I feel that the answer varies from case to case, so after reading several posts, I'm not sure in my case which is the best for my architecture.
I have a Component Library that has a Data Model and basic functionality that should be available to any application implementing this component.
I have a boundary for this component which has an interface IReader to load and process files from the disk and IDataMapper to provide Database access and CRUD operations.
a few other interfaces for specific functionality like IObjectComparison to compare objects, IXMLSerialization fro XML serialization.
I'm not sure where to store the definition of these interfaces.
The options are:
1)- Within the core Library, then when I write the implementations I will have to include the implementation libraries within this core component with I'd like to maintain decopled from the implementations.
2)- In a separate library project (Assembly). All interfaces there and included to the core component and included by the implementation libraries.
3) - In the implementation Libraries, then the core component will have to include the implementation libraries.
The only case where it seems reasonable decoupled is if I put all interfaces in a separate assembly library where Core component includes and any implementations I might need.
What do you guys think are Pros/Cons of the best option?
All I want to achieve is a decoupled architecture.
So when I do
Constructor:
CoreComponent(IReader Reader, IDataMapper Mapper)
new CoreComponent(WindowsReader, SQLServerMapper)
and don't have to include WindowsReader or SQLServerMapper into the Core Component
Cheers.
I would go for option 1 - Core Library as it is accordance with how we do in DDD. In DDD we used to put IRepository interfaces in Domain Layer instead of DAL or any other such layer.
DIP says the higher level component would own the interface, as Wikipedia says...
where interfaces defining the behavior/services required by the high-level component are owned by, and exist within the high-level component's package.
This is most common practice but not a strict rule.
Option 2 is fine but you need to refer two DLLs in other projects but with option 1 only one reference is needed. Option 3 is not appropriate.
Hope it would help. Thanks.

WCF: how to create a large number of classes in the contract?

Well, I am creating a WCF service, that have a large number of classes to communicate with the client, and this classes have also many properties.
Mainly, this classes are the POCO classes that is created with the code generator from the edmx, and I have the .tt file.
To can use this classes and properties, I have to use the DataContract and DataMember, so in each classes I have to set the DataContract and in each property of the each class the DataMemeber. So this a big work, so if I need to do some modify to the data base, I must generate again the tt file and then repeat the work.
Is there any way to do this automatically? I am using .NET 4.0 and EF 4.1.
The whole point of the .tt file being added to your project is so that you can modify the template to suit your needs. All you need to do is change the template so that it adds [DataContract] to the entity class definition and [DataMember] to the entity property definitions.
From there, any time the DB is changed you simple use the "Update model from database" feature and your entities will automatically have their code regenerated using the existing template.
All that said, I'm going to recommend you do not expose your DB entities, POCO or not, directly from your service layer. You should really be designing with domain separation and using messaging and CQRS type patterns at the service level. Then you just have some simple mapping methods that translate the data between those messages/commands to your entities.
There is Entity Framework Provider with WCF data services, might be it can help you.

Ninject with Fluent NHibernate within the Repository Layer

Due do LinqToSql not being appropriate for Many To Many relationships I am in the process of deciding to move to NHibernate (Fluent NHibernate) unless convinced otherwise...
Project Structure: UI (Mvc2 app with Ninject wiring up all services to controllers, and repositories to services), DomainServiceLayer (all util, helpers, services, domain model etc) and my Repository Layer for persistence. I have a another project call Model which basically exposes the entities, which all projects reference.
Basically I am creating my mappings within the Repository Layer with references to NHIbernate and Fluent NHIibernate, I hope to expose the interfaces to the Domain Service for querying and persisting data. How do I wire up the iSession, where do I wire it up? Any example code, what project should I put it in? Ideally I want to keep this within the Repository Layer... Is it worth learning NHibernate and going through all this?
I recommend looking at the blog posts of Bob. He describes in detail how to use the repository pattern in Ninject using NHibernate. I planned adding an example in the near future to the sample application comming with the MVC exptension as this question comes up again and again.
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/
http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/
Typically I have an NHibernateSessionFactory which is a singleton that has an OpenSession method and I bind ISession typically like this.
Bind<ISession>().ToMethod(context =>
NHibernateSessionFactory.Instance.OpenSession()).InRequestScope();
This method just calls through to ISessionFactory.OpenSession
You can put this into a NinjectModule in your repository layer, which your app can load when it creates the Kernel.
I do the configuration in the Application Layer (i.e. the top layer) as the configuration differs between applications. But it can be useful to break out some of the configuration into classes stored in the Repository Layer.
I open and close the session with an HttpModule.

Exposing existing business objects in WCF

I know there have been similar questions on this topic but I wasn't completely sure they were solving the same problem. So just to be clear...
I have an existing class library that has namespaces for types, business logic and data access. The classes in the logic and data access namespaces are static and have basic crud methods to fill the type instances with data or take type instances that are already full and do inserts or updates in the database.
Now, in addition to the existing applications that reference this library directly, I want to also create a WCF service so that other applications can consume the objects and methods that way.
Every WCF turorial that I see creates the domain objects in the service project - but I don't want my objects defined in two places.
So I was thinking I could reference serialization in my existing class library and mark the type classes as [DataContract] and the properties as [DataMember]. Then, in the WCF project, create the [ServiceContract] interfaces with [OperationContract] methods to match the static logic classes and methods from the existing library that I want to expose. Then, from the WCF project, reference the existing class library and implement the WCF interfaces by having methods in it that call the existing library logic methods which return the existing library types.
Is this a good pattern?
It sounds good but retrofitting serialization tends to be more trouble than it seems at first. I would suggest that you build some lightweight data contracts into a service layer and then build a small tier that sits between your service layer and the business layer to translate the data contracts into business objects and vice-versa.
Assuming your business object can be serialized (have attribute Serializable) one approach could be creating DataContainer object, which will be your data contract. This object would be used in your CRUD methods.
For example your interface could be
Update(DataContainer obj)
Insert(DataContainer obj)
etc.
Then you would use Binary serialization to pack your object into array of bytes and pass it this way through WCF. On the other side you would deserialize them using again BinarySerialization. You just have to make sure that both sides (client and server) have valid version of assembly with your business objects types.