WCF and Entity Framework 6 config file - entity-framework

I've a WCF service defined inside a library and a windows service which self-host this WCF service. I use Entity Framework 6 for Data Layer inside same library.
Who could confirm where I should defined connection string needed for EF?
Inside app.config of my self-hosting Windows Service? ie WindowsService.exe.config...
I want that this connection string would be available for all my WCF clients...
Thanks for your comments!

Ok, finally my issue was not related at all to app.config(s).
I didn't call correctly my WCF service.
To avoid proxies generation/use, I use ChannelFactory() in my WCF Service because I manage both servers and clients. This WCF Service is implemented throw MVVM Light with following code:
ViewModelLocator.cs:
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
//Define data access (wcf service) for design mode
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IService, Design.DesignDataService>();
}
...
}
WcfServer class:
public class WcfServer : IDisposable
{
//Wcf connection
private ChannelFactory<IService> _wcfFactory = null;
/// <summary>
/// Gets the DataService proxy from MVVMLight SimpleIOC instance.
/// </summary>
public IService DataService
{
get
{
return SimpleIoc.Default.GetInstance<IService>()??null;
}
}
/// <summary>
/// Add a Wcf server for a customer, a url and a server name
/// </summary>
/// <param name="customerName"></param>
/// <param name="serverName"></param>
/// <param name="urlServer"></param>
/// <param name=""></param>
public WcfServer(string customerName, string serverName, string urlServer)
{
_customerName = customerName;
ServerName = serverName;
UrlServer = urlServer;
}
/// <summary>
/// Connect to wcf service
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if a null exception is thrown all over Connect method</exception>
/// <exception cref="ObjectDisposedException">Thrown if an object is disposed all over Connect method</exception>
/// <exception cref="System.ServiceModel.Security.MessageSecurityException">Thrown if authentication failes with username/password over ssl</exception>
/// <exception cref="CommunicationObjectFaultedException">Faulted Exception on exception from ChannelFactory==>CreateChannel</exception>
/// <exception cref="System.InvalidOperationException">Invalid Operation Exception</exception>
/// <exception cref="Exception">Other exception</exception>
/// <returns>Returns true if connected</returns>
public bool Connect()
{
try
{
...
EndpointAddress endpointAddress = new EndpointAddress(new Uri(UrlServer));
if (_wcfFactory == null)
{
_wcfFactory = new ChannelFactory<IService>(WCFSharedConfiguration.ConfigureBindingWithSimplehttps(), endpointAddress);
//Open ChannelFactory
_wcfFactory.Open();
//Define Faulted handler
_wcfFactory.Faulted += FactoryFaulted;
}
else
//Log + return
if (!ViewModelBase.IsInDesignModeStatic)
{
//If we are not in Design (means blend or VS IDE)
SimpleIoc.Default.Register<IService>(() => _wcfFactory.CreateChannel(), true);
}
}
catch (Exception ex)
{
//Log
throw;
}
return true;
}
/// <summary>
/// Disconnect current channel
/// </summary>
/// <exception cref="TimeoutException">Timeout</exception>
/// <exception cref="CommunicationObjectFaultedException">Faulted Exception on exception from ChannelFactory==>CreateChannel</exception>
/// <exception cref="Exception">Other exception</exception>
/// <returns>True if successfull</returns>
public bool Disconnect()
{
...
}
May it helps!

Related

Unable to configure Dependency Injection - IoC in WINUI3 app - visual studio 2022

someone has the same problem using this code in the new WINUI3 app (Visual Studio 2022) as explained https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/ioc :
public sealed partial class App : Application
{
public App()
{
Services = ConfigureServices();
this.InitializeComponent();
}
/// <summary>
/// Gets the current <see cref="App"/> instance in use
/// </summary>
public new static App Current => (App)Application.Current;
/// <summary>
/// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
/// </summary>
public IServiceProvider Services { get; }
/// <summary>
/// Configures the services for the application.
/// </summary>
private static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.AddSingleton<IFilesService, FilesService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<IClipboardService, ClipboardService>();
services.AddSingleton<IShareService, ShareService>();
services.AddSingleton<IEmailService, EmailService>();
return services.BuildServiceProvider();
}
}
This is NUGET packages installed
and this is my error:
You need to install:
Microsoft.Extensions.DependencyInjection
instead of,
Microsoft.Extensions.DependencyInjection.Abstractions

Workflow Foundation Native activity child activities on designer

I've created Native Activity that looks like this:
public sealed class ConsoleColorScope : NativeActivity
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleColorScope"/> class.
/// </summary>
public ConsoleColorScope()
{
this.Color = ConsoleColor.Gray;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets Body.
/// </summary>
[DefaultValue(null)]
public Activity Body { get; set; }
/// <summary>
/// Gets or sets Color.
/// </summary>
public ConsoleColor Color { get; set; }
#endregion
#region Methods
/// <summary>
/// The execute.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
protected override void Execute(NativeActivityContext context)
{
context.Properties.Add(ConsoleColorProperty.Name, new ConsoleColorProperty(this.Color));
if (this.Body != null)
{
context.ScheduleActivity(this.Body);
}
}
#endregion
/// <summary>
/// The console color property.
/// </summary>
private class ConsoleColorProperty : IExecutionProperty
{
#region Constants and Fields
/// <summary>
/// The name.
/// </summary>
public const string Name = "ConsoleColorProperty";
/// <summary>
/// The color.
/// </summary>
private readonly ConsoleColor color;
/// <summary>
/// The original.
/// </summary>
private ConsoleColor original;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleColorProperty"/> class.
/// </summary>
/// <param name="color">
/// The color.
/// </param>
public ConsoleColorProperty(ConsoleColor color)
{
this.color = color;
}
#endregion
#region Explicit Interface Methods
/// <summary>
/// Cleanup the workflow thread.
/// </summary>
void IExecutionProperty.CleanupWorkflowThread()
{
Console.ForegroundColor = this.original;
}
/// <summary>
/// Setup the workflow thread.
/// </summary>
void IExecutionProperty.SetupWorkflowThread()
{
this.original = Console.ForegroundColor;
Console.ForegroundColor = this.color;
}
#endregion
}
}
This is class taken from the working sample:
http://code.msdn.microsoft.com/windowsdesktop/Windows-Workflow-c5649c23#content
However, when I open XAML file, I'm unable to see child activities within scope, as it is shown on the picture on the link above. All I can see is the names of the scopes.
I've created my own version of NativeActivity and I have same issue. Is there some procedure that I have to follow that would allow me to see body of NativeActivity in which I can drag and drop other activities (similar to Sequence activity) as it is shown on the demo description?
You'll need to create an Activity Designer project to go along with your custom activity which has a drop-zone (a WorkflowItemPresenter control) for placing an activity to fill your custom activity's body property with. Then you can setup the plumbing to link your designer to an activity. The following illustrates the steps in detail.
Create A New Activity Designer Project
In your solution, add a new Activity Designer project named like <Your Custom Activity Library>.Design. The assembly must be named <Your Custom Activity Library>.Design.dll, so that Visual Studio will use your activity designers for your custom activities. In the XAML for your designer, you'll utilize the WorkflowItemPresenter to display a drop-zone that accepts an activity that users of your custom activity can use.
<sap:ActivityDesigner x:Class="Your_Custom_Activity_Library.Design.ConsoleColorScopeDesigner"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">
<Grid>
<sap:WorkflowItemPresenter HintText="Drop an activity here!"
Item="{Binding Path=ModelItem.Body, Mode=TwoWay}"
MinWidth="300"
MinHeight="150" />
</Grid>
</sap:ActivityDesigner>
The ModelItem in the XAML represents your activity, and you can have your designer set any property in your activity with it. In the above sample, I'm setting up the WorkflowItemPresenter to bind to your activity's Body property.
Registering Designers With Your Activity
Next, add a class called RegisterMetadata (can be any name really) that implements the IRegisterMetadata interface. Its implementation is very simple:
public class RegisterMetadata : IRegisterMetadata
{
/// <summary>
/// Registers all activity designer metadata.
/// </summary>
public static void RegisterAll()
{
// Attribute table builder for the metadata store.
AttributeTableBuilder builder = new AttributeTableBuilder();
// Register the designer for the custom activities.
builder.AddCustomAttributes(typeof(ConsoleColorScope), new DesignerAttribute(typeof(ConsoleColorScopeDesigner)));
// Add the attributes to the metadata store.
MetadataStore.AddAttributeTable(builder.CreateTable());
}
/// <summary>
/// Registers this instance.
/// </summary>
public void Register()
{
RegisterMetadata.RegisterAll();
}
}
The way Visual Studio loads your custom activity designers is by looking for assemblies named <Your Custom Activity Library>.Design.dll, and then it looks for a public class that implements the IRegisterMetadata interface.
You should now be able to drag and drop your custom activity to a workflow and it will have a drop-zone allowing you to specify the Body activity.
You can get fancy with your designer, and expose friendly controls to allow a user to setup your custom activity. You could also create your own designers for the out-of-the-box activities provided in the .NET Framework.
Hope that helps.

Unit test Entity Framework using moq

I'm using entity framework and trying to unit test my data services which are using EF.
I'm not using repository and unit of work patterns.
I tried the following approach to mock the context and DbSet:
private static Mock<IEFModel> context;
private static Mock<IDbSet<CountryCode>> idbSet;
[ClassInitialize]
public static void Initialize(TestContext testContext)
{
context = new Mock<IEFModel>();
idbSet = new Mock<IDbSet<CountryCode>>();
context.Setup(c => c.CountryCodes).Returns(idbSet.Object);
}
I get null "Object reference not set to an instance of an object" error for idbSet "Local".
Is there any way to mock idbSet like this?
Thanks
I worked it out like this:
Created two classes named DbSetMock:
public class DbSetMock<T> : IDbSet<T>
where T : class
{
#region Fields
/// <summary>The _container.</summary>
private readonly IList<T> _container = new List<T>();
#endregion
#region Public Properties
/// <summary>Gets the element type.</summary>
public Type ElementType
{
get
{
return typeof(T);
}
}
/// <summary>Gets the expression.</summary>
public Expression Expression
{
get
{
return this._container.AsQueryable().Expression;
}
}
/// <summary>Gets the local.</summary>
public ObservableCollection<T> Local
{
get
{
return new ObservableCollection<T>(this._container);
}
}
/// <summary>Gets the provider.</summary>
public IQueryProvider Provider
{
get
{
return this._container.AsQueryable().Provider;
}
}
#endregion
#region Public Methods and Operators
/// <summary>The add.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The <see cref="T"/>.</returns>
public T Add(T entity)
{
this._container.Add(entity);
return entity;
}
/// <summary>The attach.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The <see cref="T"/>.</returns>
public T Attach(T entity)
{
this._container.Add(entity);
return entity;
}
/// <summary>The create.</summary>
/// <typeparam name="TDerivedEntity"></typeparam>
/// <returns>The <see cref="TDerivedEntity"/>.</returns>
/// <exception cref="NotImplementedException"></exception>
public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
{
throw new NotImplementedException();
}
/// <summary>The create.</summary>
/// <returns>The <see cref="T"/>.</returns>
/// <exception cref="NotImplementedException"></exception>
public T Create()
{
throw new NotImplementedException();
}
/// <summary>The find.</summary>
/// <param name="keyValues">The key values.</param>
/// <returns>The <see cref="T"/>.</returns>
/// <exception cref="NotImplementedException"></exception>
public T Find(params object[] keyValues)
{
throw new NotImplementedException();
}
/// <summary>The get enumerator.</summary>
/// <returns>The <see cref="IEnumerator"/>.</returns>
public IEnumerator<T> GetEnumerator()
{
return this._container.GetEnumerator();
}
/// <summary>The remove.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The <see cref="T"/>.</returns>
public T Remove(T entity)
{
this._container.Remove(entity);
return entity;
}
#endregion
#region Explicit Interface Methods
/// <summary>The get enumerator.</summary>
/// <returns>The <see cref="IEnumerator"/>.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this._container.GetEnumerator();
}
#endregion
}
and EFModelMock:
public class EFModelMock : IEFModel
{
#region Fields
/// <summary>The country codes.</summary>
private IDbSet<CountryCode> countryCodes;
#endregion
#region Public Properties
/// <summary>Gets the country codes.</summary>
public IDbSet<CountryCode> CountryCodes
{
get
{
this.CreateCountryCodes();
return this.countryCodes;
}
}
#endregion
#region Public Methods and Operators
/// <summary>The commit.</summary>
/// <exception cref="NotImplementedException"></exception>
public void Commit()
{
throw new NotImplementedException();
}
/// <summary>The set.</summary>
/// <typeparam name="T"></typeparam>
/// <returns>The <see cref="IDbSet"/>.</returns>
/// <exception cref="NotImplementedException"></exception>
public IDbSet<T> Set<T>() where T : class
{
throw new NotImplementedException();
}
#endregion
#region Methods
/// <summary>The create country codes.</summary>
private void CreateCountryCodes()
{
if (this.countryCodes == null)
{
this.countryCodes = new DbSetMock<CountryCode>();
this.countryCodes.Add(
new CountryCode { CountryName = "Australia", DisplayLevel = 2, TelephoneCode = "61" });
}
}
#endregion
}
Then tested like this:
[TestClass]
public class CountryCodeServiceTest
{
#region Static Fields
/// <summary>The context.</summary>
private static IEFModel context;
#endregion
#region Public Methods and Operators
/// <summary>The initialize.</summary>
/// <param name="testContext">The test context.</param>
[ClassInitialize]
public static void Initialize(TestContext testContext)
{
context = new EFModelMock();
}
/// <summary>The country code service get country codes returns correct data.</summary>
[TestMethod]
public void CountryCodeServiceGetCountryCodesReturnsCorrectData()
{
// Arrange
var target = new CountryCodeService(context);
var countryName = "Australia";
var expected = context.CountryCodes.ToList();
// Act
var actual = target.GetCountryCodes();
// Assert
Assert.IsNotNull(actual);
Assert.AreEqual(actual.FirstOrDefault(a => a.CountryName == countryName).PhoneCode, expected.FirstOrDefault(a => a.CountryName == countryName).TelephoneCode);
}
You have to set up the Local property of your idbSet mock.
For example:
idbSet = new Mock<IDbSet<CountryCode>>();
var col = new ObservableCollection<CountryCode>();
idbSet.SetupGet(x => x.Local).Returns(col);
I had been using a method to create my mock sets like this:
public static Mock<IDbSet<T>> CreateMockSet<T>(IQueryable<T> data) where T : class
{
var mockSet = new Mock<IDbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
return mockSet;
}
I merely added this line:
mockSet.Setup(x => x.Local).Returns(new ObservableCollection<T>());
before the return statement and it solved my problems.
Many of my queries look like this:
var myset = context.EntitySetName.Local.SingleOrDefault(x=>x.something==something)
??
context.SingleOrDefault(x=>x.something==something);
So I just need Local to not be null so that it doesn't throw a null reference exception.

Convert Library from ObjectContext to DbContext

I have a library (based on code found in an old blog post) that allows me to very easily wrap a façade around my data access using Entity Framework. It uses ObjectContext and has performed well enough for my purposes.
But now, we are excitedly investigating code first using DbContext and of course would like to reuse / adapt as much of our existing effort as possible.
Everything went ok naively converting our Facade enabling library with IObjectContextAdapter until we tried to utilise our facade, when the following error was received:
The type 'Employee' cannot be used as type parameter 'TEntity' in the generic type or method 'DbContextManagement.FacadeBase'. There is no implicit reference conversion from 'Employee' to 'System.Data.Objects.DataClasses.EntityObject'
MSDN says:
EntityObject derived types are not supported by the DbContext API, to use these entity types you must use the ObjectContext API.
That's fine, but how would I then go ahead completing my refactor to bypass this inability?
Here's some code (line breaks introduced):
FacadeBase.cs
namespace DbContextManagement
{
using System;
using System.Collections;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Metadata.Edm;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;
public abstract class FacadeBase<TDbContext, TEntity>
where TDbContext : DbContext, new()
where TEntity : EntityObject
{
protected TDbContext DbContext
{
get
{
if (DbContextManager == null)
{
this.InstantiateDbContextManager();
}
return DbContextManager.GetDbContext<TDbContext>();
}
}
private DbContextManager DbContextManager { get; set; }
public virtual void Add(TEntity newObject)
{
var context = ((IObjectContextAdapter)this.DbContext).ObjectContext;
string entitySetName;
if (newObject.EntityKey != null)
{
entitySetName = newObject.EntityKey.EntitySetName;
}
else
{
string entityTypeName = newObject.GetType().Name;
var container = context.MetadataWorkspace.GetEntityContainer(
context.DefaultContainerName,
DataSpace.CSpace);
entitySetName = (from meta in container.BaseEntitySets
where meta.ElementType.Name ==
entityTypeName
select meta.Name).First();
}
context.AddObject(entitySetName, newObject);
}
public virtual void Delete(TEntity obsoleteObject)
{
var context = ((IObjectContextAdapter)this.DbContext).ObjectContext;
context.DeleteObject(obsoleteObject);
}
private void InstantiateDbContextManager()
{
var objectContextManagerConfiguration =
ConfigurationManager.GetSection("DbContext") as Hashtable;
if (objectContextManagerConfiguration != null &&
objectContextManagerConfiguration.ContainsKey("managerType"))
{
var managerTypeName =
objectContextManagerConfiguration["managerType"] as string;
if (string.IsNullOrEmpty(managerTypeName))
{
throw new ConfigurationErrorsException(
"The managerType attribute is empty.");
}
managerTypeName = managerTypeName.Trim().ToLower();
try
{
var frameworkAssembly =
Assembly.GetAssembly(typeof(DbContextManager));
var managerType =
frameworkAssembly.GetType(managerTypeName, true, true);
this.DbContextManager =
Activator.CreateInstance(managerType) as DbContextManager;
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
"The managerType specified in the
configuration is not valid.", e);
}
}
else
{
throw new ConfigurationErrorsException(
"A Facade.DbContext tag or its managerType attribute
is missing in the configuration.");
}
}
}
}
EmployeeFacade.cs
namespace Facade
{
using System.Collections.Generic;
using System.Linq;
using DataModel;
using DataModel.Entities;
using DbContextManagement;
public sealed class EmployeeFacade : FacadeBase<FleetContext, Employee>
{
public Employee GetById(int? employeeId)
{
return employeeId == null
? null
: this.DbContext.Employees.FirstOrDefault(m => m.Id == employeeId);
}
}
}
Employee.cs
namespace DataModel.Entities
{
public class Employee
{
public int Id { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public string EmployeeNumber { get; set; }
}
}
If your entities are derived from EntityObject and the code you want to reuse is dependent on EntityObject based entities then it is a show stopper. You cannot use DbContext API until your entities are POCOs (no EntityObject parent).
Btw. you can use code only mapping with ObjectContext (and POCOs) without ever using DbContext. You just need to:
Create EntityTypeConfiguration or ComplexTypeConfiguration based class for each your POCO entity / complex type describing the mapping
Use DbModelBuilder to collect your configurations and call Build to get DbModel instance
Call Compile on your DbModel instance to get DbCompiledModel
Cache compiled model for lifetime of your application
When you need a new ObjectContext instance call CreateObjectContext on compiled model
Just be aware that code mapping has much more limited feature set so not everything you currently have in EDMX will be possible to achieve through code mapping.
With a very large nod to the author of the original code in the link given above, here is what I ended up with. It passes basic scenarios but I haven't yet tried out deeper navigational and related queries. Even if there is an issue, I reckon it will be bug fix rather than show stop.
Here goes. The following is reusable, works with multiple contexts and means you can go to the database and get something back in 2 lines of actual code in the client.
DataModel (Class Library Project)
Your EF Code First project with DbContext POCOs, etc.
DbContextManagement (Class Library Project)
DbContextManager.cs
namespace DbContextManagement
{
using System.Data.Entity;
/// <summary>
/// Abstract base class for all other DbContextManager classes.
/// </summary>
public abstract class DbContextManager
{
/// <summary>
/// Returns a reference to an DbContext instance.
/// </summary>
/// <typeparam name="TDbContext">The type of the db context.</typeparam>
/// <returns>The current DbContext</returns>
public abstract TDbContext GetDbContext<TDbContext>()
where TDbContext : DbContext, new();
}
}
DbContextScope.cs
namespace DbContextManagement
{
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading;
/// <summary>
/// Defines a scope wherein only one DbContext instance is created, and shared by all of those who use it.
/// </summary>
/// <remarks>Instances of this class are supposed to be used in a using() statement.</remarks>
public class DbContextScope : IDisposable
{
/// <summary>
/// List of current DbContexts (supports multiple contexts).
/// </summary>
private readonly List<DbContext> contextList;
/// <summary>
/// DbContext scope definitiion.
/// </summary>
[ThreadStatic]
private static DbContextScope currentScope;
/// <summary>
/// Holds a value indicating whether the context is disposed or not.
/// </summary>
private bool isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="DbContextScope"/> class.
/// </summary>
/// <param name="saveAllChangesAtEndOfScope">if set to <c>true</c> [save all changes at end of scope].</param>
protected DbContextScope(bool saveAllChangesAtEndOfScope)
{
if (currentScope != null && !currentScope.isDisposed)
{
throw new InvalidOperationException("DbContextScope instances cannot be nested.");
}
this.SaveAllChangesAtEndOfScope = saveAllChangesAtEndOfScope;
this.contextList = new List<DbContext>();
this.isDisposed = false;
Thread.BeginThreadAffinity();
currentScope = this;
}
/// <summary>
/// Gets or sets a value indicating whether to automatically save all object changes at end of the scope.
/// </summary>
/// <value><c>true</c> if [save all changes at end of scope]; otherwise, <c>false</c>.</value>
private bool SaveAllChangesAtEndOfScope { get; set; }
/// <summary>
/// Save all object changes to the underlying datastore.
/// </summary>
public void SaveAllChanges()
{
var transactions = new List<DbTransaction>();
foreach (var context in this.contextList
.Select(dbcontext => ((IObjectContextAdapter)dbcontext)
.ObjectContext))
{
context.Connection.Open();
var databaseTransaction = context.Connection.BeginTransaction();
transactions.Add(databaseTransaction);
try
{
context.SaveChanges();
}
catch
{
/* Rollback & dispose all transactions: */
foreach (var transaction in transactions)
{
try
{
transaction.Rollback();
}
catch
{
// "Empty general catch clause suppresses any errors."
// Haven't quite figured out what to do here yet.
}
finally
{
databaseTransaction.Dispose();
}
}
transactions.Clear();
throw;
}
}
try
{
/* Commit all complete transactions: */
foreach (var completeTransaction in transactions)
{
completeTransaction.Commit();
}
}
finally
{
/* Dispose all transactions: */
foreach (var transaction in transactions)
{
transaction.Dispose();
}
transactions.Clear();
/* Close all open connections: */
foreach (var context in this.contextList
.Select(dbcontext => ((IObjectContextAdapter)dbcontext).ObjectContext)
.Where(context => context.Connection.State != System.Data.ConnectionState.Closed))
{
context.Connection.Close();
}
}
}
/// <summary>
/// Disposes the DbContext.
/// </summary>
public void Dispose()
{
// Monitor for possible future bugfix.
// CA1063 : Microsoft.Design : Provide an overridable implementation of Dispose(bool)
// on 'DbContextScope' or mark the type as sealed. A call to Dispose(false) should
// only clean up native resources. A call to Dispose(true) should clean up both managed
// and native resources.
if (this.isDisposed)
{
return;
}
// Monitor for possible future bugfix.
// CA1063 : Microsoft.Design : Modify 'DbContextScope.Dispose()' so that it calls
// Dispose(true), then calls GC.SuppressFinalize on the current object instance
// ('this' or 'Me' in Visual Basic), and then returns.
currentScope = null;
Thread.EndThreadAffinity();
try
{
if (this.SaveAllChangesAtEndOfScope && this.contextList.Count > 0)
{
this.SaveAllChanges();
}
}
finally
{
foreach (var context in this.contextList)
{
try
{
context.Dispose();
}
catch (ObjectDisposedException)
{
// Monitor for possible future bugfix.
// CA2202 : Microsoft.Usage : Object 'databaseTransaction' can be disposed
// more than once in method 'DbContextScope.SaveAllChanges()'.
// To avoid generating a System.ObjectDisposedException you should not call
// Dispose more than one time on an object.
}
}
this.isDisposed = true;
}
}
/// <summary>
/// Returns a reference to a DbContext of a specific type that is - or will be -
/// created for the current scope. If no scope currently exists, null is returned.
/// </summary>
/// <typeparam name="TDbContext">The type of the db context.</typeparam>
/// <returns>The current DbContext</returns>
protected internal static TDbContext GetCurrentDbContext<TDbContext>()
where TDbContext : DbContext, new()
{
if (currentScope == null)
{
return null;
}
var contextOfType = currentScope.contextList
.OfType<TDbContext>()
.FirstOrDefault();
if (contextOfType == null)
{
contextOfType = new TDbContext();
currentScope.contextList.Add(contextOfType);
}
return contextOfType;
}
}
}
FacadeBase.cs
namespace DbContextManagement
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Reflection;
/// <summary>
/// Generic base class for all other Facade classes.
/// </summary>
/// <typeparam name="TDbContext">The type of the db context.</typeparam>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <typeparam name="TEntityKey">The type of the entity key.</typeparam>
/// <remarks>Not sure the handling of TEntityKey is something I've worked with properly.</remarks>
public abstract class FacadeBase<TDbContext, TEntity, TEntityKey>
where TDbContext : DbContext, new()
where TEntity : class
{
/// <summary>
/// Gets the db context.
/// </summary>
public TDbContext DbContext
{
get
{
if (DbContextManager == null)
{
this.InstantiateDbContextManager();
}
return DbContextManager != null
? DbContextManager.GetDbContext<TDbContext>()
: null;
}
}
/// <summary>
/// Gets or sets the DbContextManager.
/// </summary>
/// <value>The DbContextManager.</value>
private DbContextManager DbContextManager { get; set; }
/// <summary>
/// Adds a new entity object to the context.
/// </summary>
/// <param name="newObject">A new object.</param>
public virtual void Add(TEntity newObject)
{
this.DbContext.Set<TEntity>().Add(newObject);
}
/// <summary>
/// Deletes an entity object.
/// </summary>
/// <param name="obsoleteObject">An obsolete object.</param>
public virtual void Delete(TEntity obsoleteObject)
{
this.DbContext.Set<TEntity>().Remove(obsoleteObject);
}
/// <summary>
/// Gets all entities for the given type.
/// </summary>
/// <returns>DbContext Set of TEntity.</returns>
public virtual IEnumerable<TEntity> GetAll()
{
return this.DbContext.Set<TEntity>();
}
/// <summary>
/// Gets the entity by the specified entity key.
/// </summary>
/// <param name="entityKey">The entity key.</param>
/// <returns>Entity matching specified entity key or null if not found.</returns>
public virtual TEntity GetByKey(TEntityKey entityKey)
{
return this.DbContext.Set<TEntity>().Find(entityKey);
}
/// <summary>
/// Deletes the entity for the specified entity key.
/// </summary>
/// <param name="entityKey">The entity key.</param>
public virtual void DeleteByKey(TEntityKey entityKey)
{
var entity = this.DbContext.Set<TEntity>().Find(entityKey);
if (entity != null)
{
this.DbContext.Set<TEntity>().Remove(entity);
}
}
/// <summary>
/// Instantiates a new DbContextManager based on application configuration settings.
/// </summary>
private void InstantiateDbContextManager()
{
/* Retrieve DbContextManager configuration settings: */
var contextManagerConfiguration = ConfigurationManager.GetSection("DbContext") as Hashtable;
if (contextManagerConfiguration == null)
{
throw new ConfigurationErrorsException("A Facade.DbContext tag or its managerType attribute is missing in the configuration.");
}
if (!contextManagerConfiguration.ContainsKey("managerType"))
{
throw new ConfigurationErrorsException("dbManagerConfiguration does not contain key 'managerType'.");
}
var managerTypeName = contextManagerConfiguration["managerType"] as string;
if (string.IsNullOrEmpty(managerTypeName))
{
throw new ConfigurationErrorsException("The managerType attribute is empty.");
}
managerTypeName = managerTypeName.Trim().ToUpperInvariant();
try
{
/* Try to create a type based on it's name: */
var frameworkAssembly = Assembly.GetAssembly(typeof(DbContextManager));
var managerType = frameworkAssembly.GetType(managerTypeName, true, true);
/* Try to create a new instance of the specified DbContextManager type: */
this.DbContextManager = Activator.CreateInstance(managerType) as DbContextManager;
}
catch (Exception e)
{
throw new ConfigurationErrorsException("The managerType specified in the configuration is not valid.", e);
}
}
}
}
ScopedDbContextManager.cs
namespace DbContextManagement
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
/// <summary>
/// Manages multiple db contexts.
/// </summary>
public sealed class ScopedDbContextManager : DbContextManager
{
/// <summary>
/// List of Object Contexts.
/// </summary>
private List<DbContext> contextList;
/// <summary>
/// Returns the DbContext instance that belongs to the current DbContextScope.
/// If currently no DbContextScope exists, a local instance of an DbContext
/// class is returned.
/// </summary>
/// <typeparam name="TDbContext">The type of the db context.</typeparam>
/// <returns>Current scoped DbContext.</returns>
public override TDbContext GetDbContext<TDbContext>()
{
var currentDbContext = DbContextScope.GetCurrentDbContext<TDbContext>();
if (currentDbContext != null)
{
return currentDbContext;
}
if (this.contextList == null)
{
this.contextList = new List<DbContext>();
}
currentDbContext = this.contextList.OfType<TDbContext>().FirstOrDefault();
if (currentDbContext == null)
{
currentDbContext = new TDbContext();
this.contextList.Add(currentDbContext);
}
return currentDbContext;
}
}
}
UnitOfWorkScope.cs
namespace DbContextManagement
{
/// <summary>
/// Defines a scope for a business transaction. At the end of the scope all object changes can be persisted to the underlying datastore.
/// </summary>
/// <remarks>Instances of this class are supposed to be used in a using() statement.</remarks>
public sealed class UnitOfWorkScope : DbContextScope
{
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWorkScope"/> class.
/// </summary>
/// <param name="saveAllChangesAtEndOfScope">if set to <c>true</c> [save all changes at end of scope].</param>
public UnitOfWorkScope(bool saveAllChangesAtEndOfScope)
: base(saveAllChangesAtEndOfScope)
{
}
}
}
Facade (Class Library Project)
YourEntityFacade.cs
namespace Facade
{
using System.Collections.Generic;
using System.Linq;
using DataModel;
using DataModel.Entities;
using DbContextManagement;
public class YourEntityFacade : FacadeBase<YourDbContext, YourEntity, int>
{
public override IEnumerable<YourEntity> GetAll()
{
return base.GetAll()
.Distinct()
.ToList();
}
}
}
TestConsole (Console Application Project)
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="DbContext" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<DbContext managerType="DbContextManagement.ScopedDbContextManager" />
<connectionStrings>
<add
name="YourDbContext"
providerName="System.Data.SqlClient"
connectionString="Your connection string" />
</connectionStrings>
</configuration>
Program.cs
namespace TestConsole
{
using System;
using System.Collections.Generic;
using DataModel.Entities;
using DbContextManagement;
using Facade;
public static class Program
{
public static void Main()
{
TestGetAll();
Console.ReadLine();
}
private static void TestGetAll()
{
Console.WriteLine();
Console.WriteLine("Test GetAll()");
Console.WriteLine();
IEnumerable<YourEntity> yourEntities;
using (new UnitOfWorkScope(false))
{
yourEntities= new YourEntityFacade().GetAll();
}
if (yourEntities != null)
{
foreach (var yourEntity in yourEntities)
{
Console.WriteLine(
string.Format("{0}, {1}",
yourEntity.Id,
yourEntity.Name));
}
}
else
{
Console.WriteLine("GetAll() NULL");
}
}
}
}
So, usage is very simple and you can work with multiple contexts and facades within a scope. With this approach, the only code you are writing is custom queries. No more endless updating UnitOfWorks with repository references and authoring copy-cat repositories. I think it's great but be aware this is beta code and I'm sure it has a large hole somewhere that will need plugging :)
Thank you to all and in particular Ladislav for patience and help on this and many other related questions I ask. I hope this code is of interest. I contacted the author at the blog above but no reply yet and these days I think he's into NHibernate.
Richard

Why does Autofac fail to find log4net using the "LogInjectionModule"?

As discussed on the Autofac Wiki, the best way to automatically inject the log4net.ILog implementation for a class is to use the LogInjectionModule. This module's implementation is given in the wiki article:
public class LogInjectionModule : Module
{
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
if (registration == null) throw new ArgumentNullException("registration");
registration.Preparing += OnComponentPreparing;
}
static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var t = e.Component.Activator.LimitType;
e.Parameters = e.Parameters.Union(new[]
{
new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))
});
}
}
I'm including this module along with a module of my own to configure some components:
var builder = new ContainerBuilder();
builder.RegisterModule(new Common.Logging.LogInjectionModule());
builder.RegisterModule(new DataLayer.DataLayerModule("connectionstring"));
builder.RegisterType<SomeServiceType>();
AutofacHostFactory.Container = builder.Build();
Inside the DataLayerModule I'm constructing a type as follows:
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new DataAccess(this.ConnectionString, c.Resolve<ILog>()))
.As<IDataAccess>();
// Some other type registrations...
}
When my application attempts to construct an IDataAccess object I get the following exception:
The requested service 'log4net.ILog' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
I know that on the wiki page it is mentioned that the injection method only works for constructor injection. However I thought that was what I was doing here. Am I wrong?
Edit
On further investigation, my original answer doesn't fix your problem (I've left it below for reference). The issue is that your code bypasses the LogInjectionModule by creating a new instance of DataAccess and resolving ILog directly. This is not a usage pattern that is supported by the LogInjectionModule, which is designed to provide an ILog instance that matches the type of the instance being activated by Autofac (log4net's LogManager.GetLogger() method needs to know about the type that is using the logger).
To work around this, you have two options. The simplest is to provide the logger instance directly without using the LogInjectionModule:
builder.Register(c =>
new DataAccess(
this.ConnectionString,
LogManager.GetLogger(typeof(DataAccess)))
.As<IDataAccess>();
Alternatively (and more cleanly), you can register DataAccess in the normal Autofac way, and then register IDataAccess by using named parameters to specify the connection string that Autofac passes to the constructor. With this technique, you are enabling Autofac to use the LogInjectionModule when resolving the constructor's ILog parameter.
builder.RegisterType<DataAccess>();
builder.Register(c =>
c.Resolve<DataAccess>(
new NamedParameter("connectionString", this.ConnectionString)))
.As<IDataAccess>();
(Note that this code assumes that the connection string parameter in the DataAccess constructor is named "connectionString").
The advantage of the second technique is that your module doesn't reference log4net's LogManager class directly, so the only coupling is to the ILog interface.
Original (incorrect) answer
That code sample is for Autofac v2.0 (I originally provided the sample on that wiki page). The code for my current working module (for Autofac v2.4.5) is:
public class LogInjectionModule : ComponentInjectionModule
{
/// <summary>
/// Called when Autofac is preparing a component for activation.
/// </summary>
/// <param name = "sender">
/// The sender.
/// </param>
/// <param name = "e">
/// The <see cref = "ActivatingEventArgs{T}" /> instance containing the event data.
/// </param>
protected override void OnComponentPreparing(object sender, PreparingEventArgs e)
{
Enforce.ArgumentNotNull(e, "e");
Type t = e.Component.Activator.LimitType;
e.Parameters = e.Parameters.Union(
new[]
{
new ResolvedParameter(
(p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))
});
}
}
That code relies on my ComponentInjectionModule class which is defined below. There are some subtle differences in the way that this module hooks into the registration/activation process.
/// <summary>
/// Base module for injecting into registrations when they are prepared/activated.
/// </summary>
public class ComponentInjectionModule : IModule
{
/// <summary>
/// Apply the module to the component registry.
/// </summary>
/// <param name = "componentRegistry">
/// Component registry to apply configuration to.
/// </param>
public void Configure(IComponentRegistry componentRegistry)
{
Enforce.ArgumentNotNull(componentRegistry, "componentRegistry");
foreach (var registration in componentRegistry.Registrations)
{
this.AttachToComponentRegistration(registration);
}
componentRegistry.Registered +=
(sender, e) => this.AttachToComponentRegistration(e.ComponentRegistration);
}
/// <summary>
/// Attaches to the <see cref = "IComponentRegistration.Preparing" /> event of a component registration.
/// </summary>
/// <param name = "registration">
/// The registration whose Preparing event will be attached.
/// </param>
protected virtual void AttachToComponentRegistration(IComponentRegistration registration)
{
Enforce.ArgumentNotNull(registration, "registration");
registration.Preparing += this.OnComponentPreparing;
registration.Activating += this.OnComponentActivating;
registration.Activated += this.OnComponentActivated;
}
/// <summary>
/// Called when Autofac has activated a component.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ActivatedEventArgs{T}"/> instance containing the event data.</param>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "Not an event handler")]
protected virtual void OnComponentActivated(object sender, ActivatedEventArgs<object> e)
{
}
/// <summary>
/// Called when Autofac is activating a component.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ActivatingEventArgs{T}"/> instance containing the event data.</param>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "Not an event handler")]
protected virtual void OnComponentActivating(object sender, ActivatingEventArgs<object> e)
{
}
/// <summary>
/// Called when Autofac is preparing a component for activation.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ActivatingEventArgs{T}"/> instance containing the event data.</param>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", Justification = "Not an event handler")]
protected virtual void OnComponentPreparing(object sender, PreparingEventArgs e)
{
}
}