2017-10-05 70 views
0

是否可以使用像Castle Windsor这样的IOC框架注入启动方法。我的意思是这样的:注入启动类

public class Startup() 
{ 
    IMyObject MyObject = new MyObject(); 

    public Startup(MyObject myObject) 
    { 
     MyObject = myObject(); 
    } 
} 

我想删除并使用NHibernate启动创建数据库。另外还有一个“更好”的地方放置和使用NHibernate创建数据库?

+0

NHibernate的不支持创建和删除数据库。您可以清除架构并重新创建架构,但不能创建数据库文件。你想这样做吗? – Fran

+0

@弗兰,谢谢。我将手动创建数据库。我正在谈论创建表格。对困惑感到抱歉。你有什么建议吗? – w0051977

+0

你说的是asp.net核心启动类,对不对?检查你的标签。 –

回答

0

我使用specflow进行集成测试。

我有我在我所有的项目,看起来像这样

public abstract class NHibernateInitializer : IDomainMapper 
{ 
    protected Configuration Configure; 
    private ISessionFactory _sessionFactory; 
    private readonly ModelMapper _mapper = new ModelMapper(); 
    private Assembly _mappingAssembly; 
    private readonly String _mappingAssemblyName; 
    private readonly String _connectionString; 

    protected NHibernateInitializer(String connectionString, String mappingAssemblyName) 
    { 
     if (String.IsNullOrWhiteSpace(connectionString)) 
      throw new ArgumentNullException("connectionString", "connectionString is empty."); 

     if (String.IsNullOrWhiteSpace(mappingAssemblyName)) 
      throw new ArgumentNullException("mappingAssemblyName", "mappingAssemblyName is empty."); 

     _mappingAssemblyName = mappingAssemblyName; 
     _connectionString = connectionString; 
    } 

    public ISessionFactory SessionFactory 
    { 
     get 
     { 
      return _sessionFactory ?? (_sessionFactory = Configure.BuildSessionFactory()); 
     } 
    } 

    private Assembly MappingAssembly 
    { 
     get 
     { 
      return _mappingAssembly ?? (_mappingAssembly = Assembly.Load(_mappingAssemblyName)); 
     } 
    } 

    public void Initialize() 
    { 
     Configure = new Configuration(); 
     Configure.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new EventListener() }; 
     Configure.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new EventListener() }; 
     Configure.SessionFactoryName(System.Configuration.ConfigurationManager.AppSettings["SessionFactoryName"]); 
     Configure.DataBaseIntegration(db => 
             { 
              db.Dialect<MsSql2008Dialect>(); 
              db.Driver<SqlClientDriver>(); 
              db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; 
              db.IsolationLevel = IsolationLevel.ReadCommitted; 
              db.ConnectionString = _connectionString; 
              db.BatchSize = 20; 
              db.Timeout = 10; 
              db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'"; 
             }); 
     Configure.SessionFactory().GenerateStatistics(); 

     Map(); 
    } 

    public virtual void InitializeAudit() 
    { 
     var enversConf = new Envers.Configuration.Fluent.FluentConfiguration(); 

     enversConf.Audit(GetDomainEntities()); 

     Configure.IntegrateWithEnvers(enversConf); 
    } 

    public void CreateSchema() 
    { 
     new SchemaExport(Configure).Create(false, true); 
    } 

    public void DropSchema() 
    { 
     new SchemaExport(Configure).Drop(false, true); 
    } 

    private void Map() 
    { 
     _mapper.AddMappings(MappingAssembly.GetExportedTypes()); 
     Configure.AddDeserializedMapping(_mapper.CompileMappingForAllExplicitlyAddedEntities(), "MyWholeDomain"); 
    } 

    public HbmMapping HbmMapping 
    { 
     get { return _mapper.CompileMappingFor(MappingAssembly.GetExportedTypes()); } 
    } 

    public IList<HbmMapping> HbmMappings 
    { 
     get { return _mapper.CompileMappingForEach(MappingAssembly.GetExportedTypes()).ToList(); } 
    } 

    /// <summary> 
    /// Gets the domain entities. 
    /// </summary> 
    /// <returns></returns> 
    /// <remarks>by default anything that derives from EntityBase and isn't abstract or generic</remarks> 
    protected virtual IEnumerable<System.Type> GetDomainEntities() 
    { 
     List<System.Type> domainEntities = (from t in MappingAssembly.GetExportedTypes() 
              where typeof(EntityBase<Guid>).IsAssignableFrom(t) 
              && (!t.IsGenericType || !t.IsAbstract) 
              select t 
              ).ToList(); 

     return domainEntities; 
    } 
} 

然后在我的Global.asax Application_Begin事件处理程序继承NHibernateInitializer I类配置它

public class MvcApplication : HttpApplication 
    { 
     private const String Sessionkey = "current.session"; 
     private static IWindsorContainer Container { get; set; } 
     private static ISessionFactory SessionFactory { get; set; } 

     public static ISession CurrentSession 
     { 
      get { return (ISession) HttpContext.Current.Items[Sessionkey]; } 
      private set { HttpContext.Current.Items[Sessionkey] = value; } 
     } 

     protected void Application_Start() 
     { 
      Version version = Assembly.GetExecutingAssembly().GetName().Version; 
      Application["Version"] = String.Format("{0}.{1}", version.Major, version.Minor); 
      Application["Name"] = ConfigurationManager.AppSettings["ApplicationName"]; 

      //create empty container 
      //scan this assembly for any installers to register services/components with Windsor 
      Container = new WindsorContainer().Install(FromAssembly.This()); 

      //API controllers use the dependency resolver and need to be initialized differently than the mvc controllers 
      GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(Container.Kernel); 

      //tell ASP.NET to get its controllers from Castle 
      ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container.Kernel)); 

      //initialize NHibernate 
      ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[Environment.MachineName]; 

      if (connectionString == null) 
       throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.", 
        Environment.MachineName)); 

      if (String.IsNullOrWhiteSpace(connectionString.ConnectionString)) 
       throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.", 
        Environment.MachineName)); 

      string mappingAssemblyName = ConfigurationManager.AppSettings["NHibernate.Mapping.Assembly"]; 

      if (String.IsNullOrWhiteSpace(mappingAssemblyName)) 
       throw new ConfigurationErrorsException(
        "NHibernate.Mapping.Assembly key not set in application config file."); 

      var nh = new NHInit(connectionString.ConnectionString, mappingAssemblyName); 
      nh.Initialize(); 
      nh.InitializeAudit(); 
      SessionFactory = nh.SessionFactory; 

      AutoMapConfig.RegisterMaps(); 
      AreaRegistration.RegisterAllAreas(); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
      ModelBinderConfig.RegisterModelBinders(ModelBinders.Binders); 

      AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; 
     } 

     protected void Application_OnEnd() 
     { 
      //dispose Castle container and all the stuff it contains 
      Container.Dispose(); 
     } 

     protected void Application_BeginRequest() { CurrentSession = SessionFactory.OpenSession(); } 

     protected void Application_EndRequest() 
     { 
      if (CurrentSession != null) 
       CurrentSession.Dispose(); 
     } 
    } 
} 
+0

谢谢。当应用程序上线时你会做什么?显然你不想丢弃数据库并重新创建它。 – w0051977

+0

另外,SessionFactory在哪里声明? - 它用于Application_Start – w0051977

+0

对不起。是。他们的global.asax类有一个属性,它保存着它 – Fran