BaseService.cs
· 191 B · C#
Bruto
using NHibernate;
namespace DatabaseSample {
public class BaseService {
protected ISession _session = null;
protected ISession Session {
get { return _session; }
}
}
}
| 1 | using NHibernate; |
| 2 | |
| 3 | namespace DatabaseSample { |
| 4 | public class BaseService { |
| 5 | protected ISession _session = null; |
| 6 | |
| 7 | protected ISession Session { |
| 8 | get { return _session; } |
| 9 | } |
| 10 | } |
| 11 | } |
EmployeeService.cs
· 827 B · C#
Bruto
using DatabaseSample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseSample {
public class EmpresaService : BaseService {
public virtual void CriarEmpresas(int n) {
Console.WriteLine("CriarEmpresas({0})", n);
Contato c = new Contato("Lucas Teske", "[email protected]", "Test");
for (int i = 0; i < n; i++) {
Empresa e = new Empresa();
e.Nome = "TVS" + i;
e.Contato = c;
Session.Save(e);
}
}
public virtual void lerItems() {
Console.WriteLine("LerItems");
List<Contato> contatos = Session.CreateCriteria<Contato>().List<Contato>().ToList();
foreach (Contato c in contatos) {
Console.WriteLine("Nome: " + c.Nome);
}
}
}
}
| 1 | using DatabaseSample.Models; |
| 2 | using System; |
| 3 | using System.Collections.Generic; |
| 4 | using System.Linq; |
| 5 | using System.Text; |
| 6 | using System.Threading.Tasks; |
| 7 | |
| 8 | namespace DatabaseSample { |
| 9 | public class EmpresaService : BaseService { |
| 10 | public virtual void CriarEmpresas(int n) { |
| 11 | Console.WriteLine("CriarEmpresas({0})", n); |
| 12 | Contato c = new Contato("Lucas Teske", "[email protected]", "Test"); |
| 13 | |
| 14 | for (int i = 0; i < n; i++) { |
| 15 | Empresa e = new Empresa(); |
| 16 | e.Nome = "TVS" + i; |
| 17 | e.Contato = c; |
| 18 | Session.Save(e); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | public virtual void lerItems() { |
| 23 | Console.WriteLine("LerItems"); |
| 24 | List<Contato> contatos = Session.CreateCriteria<Contato>().List<Contato>().ToList(); |
| 25 | |
| 26 | foreach (Contato c in contatos) { |
| 27 | Console.WriteLine("Nome: " + c.Nome); |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 |
ServiceProducer.cs
· 5.8 KiB · C#
Bruto
using NHibernate;
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace DatabaseSample {
public static class ServiceProducer<T> where T: BaseService {
private static readonly string generatedSessionFactoryFieldName = "__generated_session_factory";
private static readonly string generatedTypePrefix = "__customType_";
public static T ProduceService(ISessionFactory sessionFactory) {
var myType = CompileResultType();
T data = (T)Activator.CreateInstance(myType);
myType.GetField(generatedSessionFactoryFieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(data, sessionFactory);
return data;
}
private static Type CompileResultType() {
TypeBuilder tb = GetTypeBuilder();
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
return tb.CreateType();
}
private static TypeBuilder GetTypeBuilder() {
var typeSignature = generatedTypePrefix + typeof(T).Name;
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout
, typeof(T));
FieldBuilder fieldBuilder = tb.DefineField(generatedSessionFactoryFieldName, typeof(ISessionFactory), FieldAttributes.Private);
typeof(T).GetMethods().ToList().ForEach(m => {
MethodBuilder mbM = tb.DefineMethod(m.Name, MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig,
m.ReturnType,
m.GetParameters().ToList().Select(a => a.ParameterType).ToArray());
var il = mbM.GetILGenerator();
il.DeclareLocal(typeof(ISessionFactory));
il.DeclareLocal(typeof(ISession));
il.DeclareLocal(typeof(ITransaction));
il.DeclareLocal(typeof(Exception));
if (!typeof(void).IsAssignableFrom(m.ReturnType)) {
il.DeclareLocal(m.ReturnType);
}
Label transactionNull = il.DefineLabel();
Label exit = il.DefineLabel();
// try {
il.BeginExceptionBlock();
// _session = _sessionFactory.OpenSession();
writeLine(il, "GettingSession");
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fieldBuilder);
il.Emit(OpCodes.Stloc_0);
writeLine(il, "Session got!");
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Call, typeof(ISessionFactory).GetMethod("OpenSession", new Type[0]));
il.Emit(OpCodes.Stloc_1);
writeLine(il, "Saving session");
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldloc_1);
il.Emit(OpCodes.Stfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Nop);
// transaction = _session.BeginTransaction()
writeLine(il, "Creating Transaction");
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Call, typeof(ISession).GetMethod("BeginTransaction", new Type[0]));
il.Emit(OpCodes.Stloc_2);
// base.{thismethod}({parameters})
writeLine(il, "Calling parent");
il.Emit(OpCodes.Ldarg_0);
UInt16 i = 1;
m.GetParameters().ToList().ForEach(a => {
il.Emit(OpCodes.Ldarg, i);
i++;
});
il.EmitCall(OpCodes.Call, m, new Type[0]);
if (!typeof(void).IsAssignableFrom(m.ReturnType)) {
il.Emit(OpCodes.Stloc, 4);
}
// transaction.Commit();
writeLine(il, "Commiting Transaction");
il.Emit(OpCodes.Ldloc_2);
il.Emit(OpCodes.Call, typeof(ITransaction).GetMethod("Commit"));
// } catch (Exception) {
il.BeginCatchBlock(typeof(Exception));
il.Emit(OpCodes.Pop);
// transaction.Commit();
writeLine(il, "Rolling back Transaction");
il.Emit(OpCodes.Ldloc_2);
il.Emit(OpCodes.Brfalse_S, transactionNull);
il.Emit(OpCodes.Ldloc_2);
il.Emit(OpCodes.Call, typeof(ITransaction).GetMethod("Rollback"));
writeLine(il, "Exception got!");
il.MarkLabel(transactionNull);
il.Emit(OpCodes.Rethrow);
// } finally {
il.BeginFinallyBlock();
// _session.Close();
writeLine(il, "Closing session");
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Brfalse_S, exit);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic));
il.Emit(OpCodes.Call, typeof(ISession).GetMethod("Close"));
il.Emit(OpCodes.Pop);
//}
il.EndExceptionBlock();
// return {returndata}
if (!typeof(void).IsAssignableFrom(m.ReturnType)) {
il.Emit(OpCodes.Ldloc, 4);
}
il.MarkLabel(exit);
il.Emit(OpCodes.Ret);
});
return tb;
}
private static void writeLine(ILGenerator il, string line) {
il.Emit(OpCodes.Ldstr, line);
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
}
}
}
| 1 | using NHibernate; |
| 2 | using System; |
| 3 | using System.Linq; |
| 4 | using System.Reflection; |
| 5 | using System.Reflection.Emit; |
| 6 | |
| 7 | namespace DatabaseSample { |
| 8 | public static class ServiceProducer<T> where T: BaseService { |
| 9 | |
| 10 | private static readonly string generatedSessionFactoryFieldName = "__generated_session_factory"; |
| 11 | private static readonly string generatedTypePrefix = "__customType_"; |
| 12 | |
| 13 | public static T ProduceService(ISessionFactory sessionFactory) { |
| 14 | var myType = CompileResultType(); |
| 15 | T data = (T)Activator.CreateInstance(myType); |
| 16 | myType.GetField(generatedSessionFactoryFieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(data, sessionFactory); |
| 17 | return data; |
| 18 | } |
| 19 | |
| 20 | private static Type CompileResultType() { |
| 21 | TypeBuilder tb = GetTypeBuilder(); |
| 22 | ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); |
| 23 | |
| 24 | return tb.CreateType(); |
| 25 | } |
| 26 | |
| 27 | private static TypeBuilder GetTypeBuilder() { |
| 28 | var typeSignature = generatedTypePrefix + typeof(T).Name; |
| 29 | var an = new AssemblyName(typeSignature); |
| 30 | AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); |
| 31 | ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); |
| 32 | TypeBuilder tb = moduleBuilder.DefineType(typeSignature |
| 33 | , TypeAttributes.Public | |
| 34 | TypeAttributes.Class | |
| 35 | TypeAttributes.AutoClass | |
| 36 | TypeAttributes.AnsiClass | |
| 37 | TypeAttributes.BeforeFieldInit | |
| 38 | TypeAttributes.AutoLayout |
| 39 | , typeof(T)); |
| 40 | |
| 41 | FieldBuilder fieldBuilder = tb.DefineField(generatedSessionFactoryFieldName, typeof(ISessionFactory), FieldAttributes.Private); |
| 42 | |
| 43 | typeof(T).GetMethods().ToList().ForEach(m => { |
| 44 | MethodBuilder mbM = tb.DefineMethod(m.Name, MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, |
| 45 | m.ReturnType, |
| 46 | m.GetParameters().ToList().Select(a => a.ParameterType).ToArray()); |
| 47 | |
| 48 | var il = mbM.GetILGenerator(); |
| 49 | |
| 50 | il.DeclareLocal(typeof(ISessionFactory)); |
| 51 | il.DeclareLocal(typeof(ISession)); |
| 52 | il.DeclareLocal(typeof(ITransaction)); |
| 53 | il.DeclareLocal(typeof(Exception)); |
| 54 | if (!typeof(void).IsAssignableFrom(m.ReturnType)) { |
| 55 | il.DeclareLocal(m.ReturnType); |
| 56 | } |
| 57 | |
| 58 | Label transactionNull = il.DefineLabel(); |
| 59 | Label exit = il.DefineLabel(); |
| 60 | |
| 61 | // try { |
| 62 | il.BeginExceptionBlock(); |
| 63 | |
| 64 | // _session = _sessionFactory.OpenSession(); |
| 65 | writeLine(il, "GettingSession"); |
| 66 | il.Emit(OpCodes.Nop); |
| 67 | il.Emit(OpCodes.Ldarg_0); |
| 68 | il.Emit(OpCodes.Ldfld, fieldBuilder); |
| 69 | il.Emit(OpCodes.Stloc_0); |
| 70 | |
| 71 | writeLine(il, "Session got!"); |
| 72 | il.Emit(OpCodes.Ldloc_0); |
| 73 | il.Emit(OpCodes.Call, typeof(ISessionFactory).GetMethod("OpenSession", new Type[0])); |
| 74 | il.Emit(OpCodes.Stloc_1); |
| 75 | |
| 76 | writeLine(il, "Saving session"); |
| 77 | il.Emit(OpCodes.Ldarg_0); |
| 78 | il.Emit(OpCodes.Ldloc_1); |
| 79 | il.Emit(OpCodes.Stfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic)); |
| 80 | il.Emit(OpCodes.Nop); |
| 81 | |
| 82 | // transaction = _session.BeginTransaction() |
| 83 | writeLine(il, "Creating Transaction"); |
| 84 | il.Emit(OpCodes.Ldarg_0); |
| 85 | il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic)); |
| 86 | il.Emit(OpCodes.Call, typeof(ISession).GetMethod("BeginTransaction", new Type[0])); |
| 87 | il.Emit(OpCodes.Stloc_2); |
| 88 | |
| 89 | |
| 90 | // base.{thismethod}({parameters}) |
| 91 | writeLine(il, "Calling parent"); |
| 92 | il.Emit(OpCodes.Ldarg_0); |
| 93 | UInt16 i = 1; |
| 94 | m.GetParameters().ToList().ForEach(a => { |
| 95 | il.Emit(OpCodes.Ldarg, i); |
| 96 | i++; |
| 97 | }); |
| 98 | |
| 99 | il.EmitCall(OpCodes.Call, m, new Type[0]); |
| 100 | if (!typeof(void).IsAssignableFrom(m.ReturnType)) { |
| 101 | il.Emit(OpCodes.Stloc, 4); |
| 102 | } |
| 103 | |
| 104 | // transaction.Commit(); |
| 105 | writeLine(il, "Commiting Transaction"); |
| 106 | il.Emit(OpCodes.Ldloc_2); |
| 107 | il.Emit(OpCodes.Call, typeof(ITransaction).GetMethod("Commit")); |
| 108 | |
| 109 | // } catch (Exception) { |
| 110 | il.BeginCatchBlock(typeof(Exception)); |
| 111 | il.Emit(OpCodes.Pop); |
| 112 | |
| 113 | // transaction.Commit(); |
| 114 | writeLine(il, "Rolling back Transaction"); |
| 115 | il.Emit(OpCodes.Ldloc_2); |
| 116 | il.Emit(OpCodes.Brfalse_S, transactionNull); |
| 117 | il.Emit(OpCodes.Ldloc_2); |
| 118 | il.Emit(OpCodes.Call, typeof(ITransaction).GetMethod("Rollback")); |
| 119 | writeLine(il, "Exception got!"); |
| 120 | il.MarkLabel(transactionNull); |
| 121 | il.Emit(OpCodes.Rethrow); |
| 122 | |
| 123 | |
| 124 | // } finally { |
| 125 | il.BeginFinallyBlock(); |
| 126 | // _session.Close(); |
| 127 | writeLine(il, "Closing session"); |
| 128 | il.Emit(OpCodes.Ldarg_0); |
| 129 | il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic)); |
| 130 | il.Emit(OpCodes.Brfalse_S, exit); |
| 131 | il.Emit(OpCodes.Ldarg_0); |
| 132 | il.Emit(OpCodes.Ldfld, typeof(BaseService).GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic)); |
| 133 | il.Emit(OpCodes.Call, typeof(ISession).GetMethod("Close")); |
| 134 | il.Emit(OpCodes.Pop); |
| 135 | //} |
| 136 | il.EndExceptionBlock(); |
| 137 | |
| 138 | // return {returndata} |
| 139 | if (!typeof(void).IsAssignableFrom(m.ReturnType)) { |
| 140 | il.Emit(OpCodes.Ldloc, 4); |
| 141 | } |
| 142 | |
| 143 | il.MarkLabel(exit); |
| 144 | il.Emit(OpCodes.Ret); |
| 145 | }); |
| 146 | |
| 147 | return tb; |
| 148 | } |
| 149 | |
| 150 | private static void writeLine(ILGenerator il, string line) { |
| 151 | il.Emit(OpCodes.Ldstr, line); |
| 152 | il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 |