2017-10-05 2 views
0

Ist es möglich, ein IOC-Framework wie Castle Windsor zu verwenden, um in die Startup-Methode zu injizieren. Ich meine etwas in der Art:In die Startup-Klasse injizieren

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

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

Ich versuche zu löschen und erstellen Sie eine Datenbank beim Start mit NHibernate. Gibt es alternativ einen "besseren" Ort zum Löschen und Erstellen der Datenbank mit NHibernate?

+0

nhibernate nicht unterstützt Datenbank erstellen und löschen. Sie können ein Schema löschen und das Schema neu erstellen, aber nicht die Datenbankdatei. Willst du das machen? – Fran

+0

@Fran, danke. Ich werde die Datenbank manuell erstellen. Ich spreche über die Erstellung der Tabellen. Entschuldigung für die Verwirrung. Hast du irgendwelche Vorschläge? – w0051977

+0

Sie sprechen über die asp.net Kern-Startup-Klasse, oder? Überprüfen Sie Ihre Tags. –

Antwort

0

Ich mache so etwas für Integration Tests mit specflow.

Ich habe eine NHibernateInitializer Klasse, die ich in all meinen Projekten erben, wie diese Handler konfigurieren

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; 
    } 
} 

Da ist in meinem global.asax Application_Begin Ereignis sieht ich es

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

Danke. Was machen Sie, wenn die Anwendung online geht? Offensichtlich möchten Sie die Datenbank nicht löschen und neu erstellen. – w0051977

+0

Wo wird auch SessionFactory deklariert? - Es wird in Application_Start verwendet – w0051977

+0

Entschuldigung. Ja. Es gibt eine Eigenschaft auf ihrer global.asax-Klasse, die es enthält – Fran