Search code examples
c#nhibernatemedium-trust

SecurityException when mapping inheritance with Fluent NHibernate under Medium trust


I'm having problems mapping inheritance in my application running under Medium trust. It works like a charm when I remove Medium trust restrictions from web.config. If I comment out my subclass mappings, all goes well too.

When my application starts in Medium trust, during Fluent's configuration building, I catch exception from which I can read that System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(...) method has no permissions to run.

Every bit of information I can find suggests pre-generating lazy proxies, turning lazy loading off and disabling reflection optimizer. I've done all that preparation, and my code works if I don't map subclasses.

Here are my mappings:

public PageMap()
    {
        Id(x => x.PageID);
        Map(x => x.DateCreated);
        Map(x => x.DateLastAccessed);
        Map(x => x.Hits);
        Map(x => x.PrivateSuffix);
        Map(x => x.PublicSuffix);
        HasMany(x => x.Components).Not.LazyLoad();
        Not.LazyLoad();
    }
}

public class ComponentMap: ClassMap<Component>
{
    public ComponentMap()
    {
        Id(x => x.ComponentID);
        Map(x => x.Position);
        References(x => x.Page);
        DiscriminateSubClassesOnColumn("ComponentType");
        Not.LazyLoad();
    }
}

public class HeadingComponentMap : SubclassMap<HeadingComponent>
{
    public HeadingComponentMap()
    {
        Map(x => x.Text);
        Not.LazyLoad();
    }
}

and a relevant part from web.config

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<bytecode-provider type="null"/>
<reflection-optimizer use="false" />

<session-factory name="">
  <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
  <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
  <property name="connection.connection_string">data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|entities.mdf;User Instance=true</property>
  <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
  <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
  <property name='current_session_context_class'>web</property>
</session-factory>

Will I have to do everything manually? I would very much like to use inheritance here.


Solution

  • I wasn't able to solve the original problem, but the answer that AlexCuse gave led me to a workaround.

    When I change the model I export mappings using

    .Mappings(
        m => m.FluentMappings.AddFromAssemblyOf<SessionManager>()
        .ExportTo("mappings")
    )
    

    and after embedding mappings as resources i map using

    .Mappings(
        m => m.HbmMappings.AddFromAssemblyOf<SessionManager>()
    )