хорошее / простое приложение mpc asp.net с беглым nhibernate - PullRequest
2 голосов
/ 17 июня 2010

Где я могу найти хорошее / простое приложение asp.net mvc с беглой nhibernate?Любое предложение ..

Ответы [ 2 ]

16 голосов
/ 19 июня 2010

Я написал пример приложения ASP.NET MVC , которое использует FluentNHibernate среди других сред с открытым исходным кодом. Исходный код доступен на github .


В соответствии с просьбой в разделе комментариев я попытался обобщить важные части настройки FluentNhibernate с ASP.NET MVC:

Начните с определения вашей модели:

public class User
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual int? Age { get; set; }
}

Тогда хранилище, которое позволит вам получить доступ к модели:

using System.Collections.Generic;

public interface IUsersRepository
{
    IEnumerable<User> GetUsers();
    User Get(int id);
    void Delete(int id);
    int Save(User user);
    void Update(User user);
}

Затем внедрите этот репозиторий:

using System.Collections.Generic;
using Spring.Data.NHibernate.Generic.Support;

public class SqlUsersRepository : HibernateDaoSupport, IUsersRepository
{
    public IEnumerable<User> GetUsers()
    {
        return HibernateTemplate.LoadAll<User>();
    }

    public User Get(int id)
    {
        return HibernateTemplate.Get<User>(id);
    }

    public void Delete(int id)
    {
        HibernateTemplate.Delete(new User { Id = id });
    }

    public int Save(User user)
    {
        return (int)HibernateTemplate.Save(user);
    }

    public void Update(User user)
    {
        HibernateTemplate.Update(user);
    }
}

Пока что нет отдельных частей FluentNHibernate. Давайте теперь определим отображение:

using FluentNHibernate.Mapping;

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id, "usr_id");
        Map(x => x.FirstName, "usr_firstname");
        Map(x => x.LastName, "usr_lastname");
        Map(x => x.Age, "usr_age");
    }
}

И фабрика сессий Spring.NET, которая использует SQLite, но вы можете адаптировать ее по мере необходимости:

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using Spring.Data.NHibernate;

public class FluentSessionFactory : LocalSessionFactoryObject
{
    private readonly string _dataFile;
    public FluentSessionFactory(string dataFile)
    {
        _dataFile = dataFile;
    }

    protected override ISessionFactory NewSessionFactory(Configuration config)
    {
        return Fluently
            .Configure()
            .Database(
                SQLiteConfiguration
                    .Standard
                    .UsingFile(_dataFile)
                    .ProxyFactoryFactory<ProxyFactoryFactory>()
            ).Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
            ).BuildSessionFactory();
    }
}

Далее мы определим контроллер:

public class HomeController : Controller
{
    private readonly IUsersRepository _repository;
    public HomeController(IUsersRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View(_repository.GetUsers());
    }
}

Как только у нас все это на месте, нам нужно соединить все вместе. Поскольку мы используем Spring.NET, нам нужно предоставить собственную фабрику контроллеров:

public class SpringControllerFactory : DefaultControllerFactory
{
    private static readonly IApplicationContext _springContext = ContextRegistry.GetContext();

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType != null)
        {
            var objectsOfType = _springContext.GetObjectsOfType(controllerType);
            if (objectsOfType.Count > 0)
            {
                return (IController)objectsOfType.Cast<DictionaryEntry>().First<DictionaryEntry>().Value;
            }
        }
        return base.GetControllerInstance(requestContext, controllerType);
    }
}

Далее идет web.config:

<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="~/Config/springContext.xml"/>
    </context>
  </spring>


  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>

    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

И, наконец, springContext.xml:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object
    id="siteRoot"
    type="System.Web.Hosting.HostingEnvironment, System.Web"
    factory-method="get_ApplicationPhysicalPath" />

  <object
    id="dataFile"
    type="System.IO.Path, mscorlib"
    factory-method="Combine">
    <constructor-arg name="path1" ref="siteRoot" />
    <constructor-arg name="path2" value="App_Data\data.db3" />
  </object>

  <object id="sessionFactory" type="AppName.Business.Repositories.FluentSessionFactory, AppName">
    <constructor-arg name="dataFile" ref="dataFile" />
  </object>

  <object id="sqlUsersRepository"
        type="AppName.Business.Repositories.SqlUsersRepository, AppName"
        singleton="false">
    <property name="SessionFactory" ref="sessionFactory"/>
  </object>

  <object id="home"
          type="AppName.Controllers.HomeController, AppName"
          singleton="false">
    <constructor-arg name="repository" ref="sqlUsersRepository" />
  </object>

</objects>
4 голосов
/ 17 июня 2010

В проекте Orchard CMS используется свободный nhibernate.

http://orchard.codeplex.com/

...