How to structure large .NET project using an ORM

Status
Not open for further replies.

KarlShea

Ars Tribunus Militum
2,277
Subscriptor++
So I'm going to be doing a rewrite of a project, going from .NET 1.1 to .NET 3.5, and to the newest version of NHibernate.

My question involves how to structure the project in order to use the cool stuff from NHibernate while still doing sort of an "n-tier" project.

The reason being, there are a couple of separate projects all using the same database:
  • Public website, which is really read-only, with maybe an email sign-up form or whatever.
  • Data import console app
  • Private "intranet" website, which is read/write
  • Data export console app
  • Web services/image host, which is really read-only but might have one or two write methods
  • Another public website that will communicate only with the web services host, but would be nice to use the same objects and managers (or at least the same IManagers, if that's the way I go). However, in the old project it's using a separate set of objects and managers that just talk to the web service site, and that's totally okay with me. The reason it would be nice to have both is to maybe have a separate control library to display things between the public and web service sites.

I seem to remember way back when I was doing some Java, the big thing was doing IoC and using Spring and Hibernate to kind of plug all this stuff together so it worked all slick, but I'm having a hard time finding examples of how to set this stuff up in the .NET 3.5 world. I'm really open to a lot of ideas, as long as I'm able to make all of those different things above work together :)

I'd even be open to not using Hibernate if there was a compelling reason not to, but I'm STRONGLY against using the generated-code Entity framework solution requiring me to walk through wizards to get stuff to work. POCO's only, please. Also, having to modify 6 different files every time I want to add a method to a DAO is pretty janky IMHO.

So how should I do this?
 

KarlShea

Ars Tribunus Militum
2,277
Subscriptor++
Well, I learned Java web programming starting with Hibernate 2, and we used NHibernate 1.2 with the old project, so I'm pretty comfortable with it and how it performs with the data that I'm working with.

I guess really where I'm stuck is that the example code I've been seeing is either really simplistic where it's not going to be able to do what I need it to do, or it's way way too "enterprisey" and has that terrible hundreds-of-hours-to-do-something bad smell about it. I'm not able to find a middle-of-the-road example app that kind of ties together some best practices while still being a bit agile.
 
Is your application mostly "screens over data"? If so you might want to consider just going with something like an ActiveRecord implementation and avoid nHibernate entirely since it may not be necessary.

If your application is "behaviour rich" and has alot of domain behaviour and complex domain models then you might want to consider adopting some of the patterns from Domain Driven Design such as the repository pattern which nHibernate fits in very nicely with.
 
You could go with Fluent NHibernate (this gives you ability to use an auto model that conventionally deduces mappings with ability for overruling these selectively) + StructureMap or Autofac for IoC. Both of these containers allow for dynamic proxy, interception (which opens up for AOP), Func<T> factory ctor injection, named registrations and lifetime scope management. Convention based registrations and so on.

Keep your DB plumbing code in an Infrastructure library - use another library for interfaces of services, and repository interface to hide usage of NHibernate specific repository, like some sort of generic Repository<T> pattern, and use some sort of initializer or bootstrapper library to kick IoC bindings together and other init's into life. I would use a specification / query pattern in conjunction with the repository, or split the repository up into a Retriever<TDTO> part (use Automapper to go from TDTO to T and vice verca) and a Persister<T> part.

If your app is more behavior than data dump CRUD, then you could consider looking into architectural patterns/concepts like domain driven design and command query responsibility segregation. NHibernate can still be used in such an environment.
 
KarlShea":1rvb2dox said:
Is IoC the way to go with this project? Is it going to work with NHibernate, or am I going to lose the lazy loading stuff?

That's really what my question is... how does everyone do this in the .NET world now? Or has it gotten to "use microsoft's wizard crap or roll your own"?

Yes, you can go IoC with this and I recommend it, given your requirements on app structure - IoC gives you the ability to get better app design as it facilitates SOLID code - and no, lazy loading stuff has nothing to do with utilization of IoC (you can even set NH up such that it can utilize your IoC of choice and ctor inject dependencies into your entities, however I would not do such a thing normally) - in fact you can find examples of configuration of NHibernate (or any other ORM for that sake) with an IoC container. Utilizing an IoC + some sort of repository pattern makes it easy to mock/stub away the repository when unit testing code that depends on such a thing. Furthermore, utilizing IoC can make your app much more dynamic in behavior as you can have the container return different implementations or setup depending on runtime context.

Seems like you should read a few tutorials on StructureMap w.r.t. dependency injection as this would help you a lot. Autofac is also nice, but StructureMap has more and better documentation.

If you are going IoC, then be aware of not falling into the service locator anti-pattern, e.g. don't use it all over your code e.g. inside methods or ctor (it makes code harder to test), that is why the containers give you things like ctor, property and func<t> injection. You optimally just use the service locator in very few places, just to kick life into highlevel services that depend on other things, an example could be an IoC based ControllerFactory in a MVC web app.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
Here is what I do, and recommend. Although, I would be SUPREMELY appreciative if someone can improve this.

For the record, I typically use NHibernate with Unity as my IoC container.

Let's assume you work for a company called Fook Systems, and your project is called Dis:

You should have a solution with the following projects:

Fook.Dis.Domain - Class library project. This contains your POCOs. Simple entity classes or interfaces, as well as interfaces defining your repositories. This project will have two folders (and thus two further namespaces). The folders are "Models" and "Repositories".

Fook.Dis.Domain.NHib - Class library project. This contains your .hbm.xml mapping files as well as implementations of your repository interfaces. Again, I would put two folders in this project to mirror the "Models" and "Repositories" namespaces. If you decide to use another ORM that supports POCOs you would simply use a project/namespace like: Fook.Dis.Domain.SubSonic, Fook.Dis.Domain.EF, etc.

Now, the above is kind of at a minimum. Depending on the complexity of your application you could also have:

Fook.Dis.Services - Class library project. This contains your service/business layer. You can bake in more complex business logic. If used, this is the ONLY layer your application would access. It would be a client of the Fook.Dis.Domain library.

Now, when you are doing your IoC/DI at the application level, I would suggest using the Service Locator pattern. You can find a good implementation of this pattern in the Common Service Locator library. There is an "adapter" for Unity or just about any other IoC container you will encounter.

The service locator will essentially abstract your chosen IoC container from your application and still give you all the tangible benefits of IoC/DI.

Now, as a bit of assistance you may consider using a base interface for you repositories, here is a subset of one that I use:

Code:
namespace Fook.Dis.Domain.Repositories
{
    public interface IRepository<TEntity, TIdentity>
    {
        IQueryable<TEntity> Entities { get; }

        void Save(TEntity entity);

        void Delete(TEntity entity);

        TEntity Find(TIdentity id);        
    }
}

The above gives you basic crud and simple ID based lookup. It also gives you, via the Entities property, LINQ support.

You would simply derive from this interface for your other repository interface definitions:

Code:
namespace Fook.Dis.Domain.Repositories
{
    //very simplistic, crud only entity
    public interface IOrderRepository : IRepository<Order, Guid>
    {
        
    }

    //crud entity with extra methods defined
    public interface IAppointmentRepository : IRepository<Appointment, Guid>
    {
       IList<Appointment> SomeFancySearchViaNamedQueryOrWhatever(string arg1, long arg2);
    }
}

Now, you obviously need to implement the base IRepository interface in your Fook.Dis.Domain.NHib project, but it isn't all that hard and you can then quickly spit out the other repositories.

Anyway, that's all I've got for you at this point. Depending on the complexity of the project you could have some other handy class libraries, but this is a good start.

EDIT: Here is some further clarification.

Your Fook.Dis.Services project should only ever refer to Fook.Dis.Domain. It should not do anything ORM specific and shouldn't be referencing the Fook.Dis.Domain.NHib project at all.

Further, let's say we have a service class the needs access to the IOrderRepository. It should be defined something like:

Code:
namespace Fook.Dis.Services
{
    public class OrderService
    {
        protected IOrderRepository OrderRepo { get; set; }

        public OrderService(IOrderRepository orderRepository) 
        {
            OrderRepo = orderRepository;
        }

        public void SoemthingSpecialJustForYou(Order order, long arg1, string[] whoKnows)
        {
            //do something with the IOrderRepository
        }
    }
}

Again, in your application code I recommend service locator. It is pretty safe to use as long as you keep it confined to your application layer. You shouldn't be accessing it inside of your Fook.Dis.Services or Fook.Dis.Domain projects at all.

Of course, if you are using an application framework that is heavily IoC/DI oriented such as ASP.NET MVC then this is pretty easy. Just like the OrderService class, your controllers will have dependencies defined and you'd just set up your MVC application to use the service locator when your controllers are being requested from the controller factory.
 

martin007

Ars Tribunus Militum
2,783
For solid enterprise grade architecture guidance, I would recommend looking at the Sharp Architecture (http://sharparchitecture.net/) and "Who Can Help Me" (http://whocanhelpme.codeplex.com/).

The former is an opinionated framework for ASP.NET MVC (with heavy emphasis on facilitating the "M") based on ALT.NET holy grail stack (DDD, POCOs, IoC, NHibernate, etc), and the latter is a sample application based off of it that has a much more robust DDD oriented architecture.

You'll also be able to re-use the core and hook up different end point clients (check out the WCF samples).

I'd say this is your best bet. These represent the current "best practice" in .NET architecture (honestly, that's not saying much lol).

If you're adventurous you can look into CQRS/DDDD, event sourcing, and object databases, but these are still on the alpha geek curve in the .NET world.

If you value your sanity, avoid EF for now (at least until v4 has more traction), and forget about the old school frameworks like CSLA and the Microsoft P&P guidance stuff. (Others have mentioned P&P Prism. It's actually good, but is not suited for server side web archs).

Hope this helps!
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
(Others have mentioned P&P Prism. It's actually good, but is not suited for server side web archs).
Assuming it has to be native html/js, anyway. The SL version of Prism does have near-parity with the main (WPF) version.

Regardless, it's designed to be modular, unlike the old P&P guidance in which each "block" was somewhat heavyweight and/or coupled (if only implicitly) to the others. In other words it's painless to use just the IoC stuff, or the exceptions/logging library, or what have you.
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
KarlShea":hgaop3z7 said:
Thanks for all the recs guys, I've done a lot of reading up on some of the IoC stuff and all the libraries linked to in the last couple of days.

What's everyone's opinion on ASP.NET MVC? Is it worth the effort to use if you're losing the ViewState and all of the associated page flow stuff?

ViewState, SessionState, etc are crutches that will cripple your application's scalability, portability, and testability.

ASP.NET MVC is honestly much easier to work with once you are over the initial hump and will get in your way far less often.
 
Status
Not open for further replies.