Why does Breeze.WebApi.EFContextProvider fail to cast to DbContext? - breeze

I'm using breeze to access data via an entity-framework server -- basically the default for breeze. In my tests, I get the following runtime server error:
System.InvalidCastException: Unable to cast object of type 'SLN.Controllers.Context' to type 'System.Data.Entity.DbContext'.
at Breeze.WebApi.EFContextProvider`1.get_Context()
This is very odd since 1) my SLN.Controllers.Context class does subclass System.Data.Entity.DbContext and 2) I don't get this error in the product (non-test) environment.
Note that the error comes from the EFContextProvider class of Breeze.WebApi.dll which provides much of the server implementation. EFContextProvider class has a generic parameter which I passed as SLN.Controllers.Context. The EFContextProvider instance must instantiate my Context (since I don't) and then it must try to cast it to System.Data.Entity.DbContext.
How could this cast fail? How can it work in non-test, but fail in test?
UPDATE
Per request, here are the parts of my code that are related to the runtime error.
public class Context : DbContext {...}
[BreezeController]
public class TruDBController : ApiController
{
private class ContextProvider : EFContextProvider<Context>
{
...
}
private readonly EFContextProvider<Context> _contextProvider = new ContextProvider();
private EFContextProvider<Context> Provider
{
get {return _contextProvider;}
}
[HttpGet]
public IQueryable<Models.Table1> Table1()
{
// error occurs on get of Context from Provider
return Provider.Context.Table1;
}
}
The cast is in the breeze EFContextProvider class Context property:
public T Context {
get {
if (_context == null) {
_context = CreateContext();
// Disable lazy loading and proxy creation as this messes up the data service.
if (typeof(ObjectContext).IsAssignableFrom(typeof(T))) {
var objCtx = (ObjectContext)(Object)_context;
objCtx.ContextOptions.LazyLoadingEnabled = false;
} else {
var dbCtx = (DbContext)(Object)_context; // HERE??
dbCtx.Configuration.ProxyCreationEnabled = false;
dbCtx.Configuration.LazyLoadingEnabled = false;
}
}
return _context;
}
}

Related

Structuremap config with runtime value ...For<IProductProvider>().Use<ProductProvider>.Ctor<string>("connectionString").Is(someValueAtRunTime);

Structuremap experts,
I found this post on stackoverflow ...
Passing constructor arguments when using StructureMap
Someone suggested to use the StructureMap configuration with runtime value like this
For<IProductProvider>().Use<ProductProvider>.Ctor<string>("connectionString").Is(someValueAtRunTime);
But example is not adequate enough to understand its declaration and usage. I try to find on StructureMap site as well but not much help ...
In my situation, I want to pass on the dependency of concrete DbContext (IDbContext) to the constructor of the class with connection string dynamically created during run time within that class.
Finally I managed to make it working ...
Here how I did it ...
Hope it will help someone, and thanks to PHeiberg for answer me before and showing me right direction.
Interface Definition
public interface ICreditCard
{
string GetName();
}
public interface IAdditionalCreditCard : ICreditCard
{
}
public class AdditionalCreditCard : IAdditionalCreditCard
{
private readonly string _name;
public AdditionalCreditCard(string name)
{
_name = name;
}
public string GetName()
{
return _name;
}
}
Define function in Structure map config code
Func<string, IAdditionalCreditCard> additionalCreditCard = value =>
ObjectFactory.With("name").EqualTo(value).GetInstance<AdditionalCreditCard>();
Add following configuration in ObjectFactory.Configure
ObjectFactory.Configure(config =>
{
config.For<Func<string, IAdditionalCreditCard>>().Use(additionalCreditCard);
});
And in code ...
public class PaymentSystem
{
private readonly Func<string, IAdditionalCreditCard> _addtionalCreditCard;
private IAdditionalCreditCard _addCreditCard;
public PaymentSystem(Func<string, IAdditionalCreditCard> additionalCredit)
{
_addtionalCreditCard = additionalCredit;
}
public string AddtionalSystemType()
{
_addCreditCard = _addtionalCreditCard("American Express");
return _addCreditCard.GetName();
}
}
The code you are posting is supposed to go in the setup code for StructureMap, which can go in the Initialize/Configure method or a Registry. The setup code is normally executed only once in the application's life cycle. So if you know the connection string value when the application is stared and you configure StructureMap, you can put the code you posted in the initialization of StructureMap. If the value is not known until later on, you need some kind of factory approach.
A factory approach could be done like this (in your StructureMap configuration code):
Func<string, IDbContext> createContext = value => {
/* create context based on value */
};
ObjectFactory.Initialize(c => {
For<Func<string, IDbContext>>().Use(createContext);
// The rest of you configuration ...
});
You can now use the Func to create an instance of the context when you need it:
public class ProductProvider : IProductProvider
{
private readonly Func<string, IDbContext> _contextCreator;
public ProductProvider(Func<string, IDbContext> contextCreator)
{
_contextCreator = contextCreator;
}
public IEnumerable<Product> GetProducts(string someValue)
{
using(var context = contextCreator(someValue))
{
return SomeOperationOnThe(context);
}
}
}

Ninject Binding Constraint that searches up to find a type

I've got a class hierarchy like this (simplified):
class Connection
{
}
interface IService<T>
{
}
class ServiceImplementation : IService<int>
{
public ServiceImplementation(Connection)
{
}
}
interface IConnectionConfiguration
{
public void Configure(Connection c)
}
class ConnectionConfiguration : IConnectionConfiguration
{
public void Configure(Connection c)
}
Where I have multiple implementations of IConnectionConfiguration and IService. I am wanting to create a provider/bindings which:
constructs a new instance of Connection.
GetAll and applies that to the Connection.
Bindings specify which IConnectionConfiguration implementations to be used, based on
on the type of IService to be constructed
Currently I have a provider implementation like this:
public Connection CreateInstance(IContext context)
{
var configurations = context.Kernel.GetAll<IConnectionConfiguration>()
var connection = new Connection();
foreach(var config in configurations)
{
config.Configure(connection);
}
return connection;
}
But when I try to make the contextual binding for IConnectionConfiguration it doesn't have a parent request or parent context...
Bind<IConnectionConfiguration>().To<ConcreteConfiguration>().When(ctx => {
// loop through parent contexts and see if the Service == typeof(IService<int>);
// EXCEPT: The ParentRequest and ParentContext properties are null.
});
What am I doing wrong here? Can I do this with ninject?
By calling kernel.GetAll you are creating a new request. It has no information about the service context. There is an extension that allows you to create new requests that preserve the original context (Ninject.Extensions.ContextPreservation)
See also https://github.com/ninject/ninject.extensions.contextpreservation/wiki
context.GetContextPreservingResolutionRoot().GetAll<IConnectionConfiguration>();

Passing in the type of the declaring class for NLog using Autofac

Following on from this question I would like autofac to inject the type of the declaring object into the constructor of my NLog service, so that it can correctly log which type is logging entries.
My NLogService class looks like this...
public class NLogService : ILogService
{
private readonly Logger _logger;
public NLogService(Type t)
{
var consumerType = t.DeclaringType.FullName;
_logger = LogManager.GetLogger(consumerType);
}
However it fails on app startup because it obviously cannot work out what to inject into the constructor of the NLogService with the following error...
None of the constructors found with
'Public binding flags' on type
'MyProduct.Domain.Services.Logging.NLogService'
can be invoked with the available
services and parameters: Cannot
resolve parameter 'System.Type t' of
constructor 'Void .ctor(System.Type)'.
So, my question is - how do i instruct autofac to inject the type of the calling class?
I tried this...
public NLogService(Type t)
{
var method = MethodBase.GetCurrentMethod();
Type consumingType = method.DeclaringType;
var consumerType = consumingType.FullName;
var consumerType = t.DeclaringType.FullName;
_logger = LogManager.GetLogger(consumerType);
}
But i just end up with MyProduct.Domain.Services.Logging.NLogService
What i want is the type of the class that is doing the actual logging.
i have already tried this suggestion and it didnt work for me either.
Could make your NLogService generic, i.e. NLogService<T> and use Autofac's open generics support?
Then you could do this:
public class NLogService<T> : ILogger<T>
{
private readonly Logger _logger;
public NLogService()
{
_logger = LogManager.GetLogger(typeof(T).FullName);
}
}
There is no real good way to do this with Autofac, because does not have support for 'context based injection' (which is what you are trying to do). There is a workaround, but it aint pretty...
What you can do is revert to property injection and define a base class or interface for that ILogService property. For instance, you can define the following interface:
public interface ILoggerContainer
{
public ILogService Logger { get; set; }
}
Now you can implement this interface on all types that need a logger:
public class Consumer : IConsumer, ILoggerContainer
{
public ILogService Logger { get; set; }
}
With this in place you can configure Autofac as follows:
builder.RegisterType<ILoggerContainer>()
.OnActivating(e =>
{
var type = typeof(LogService<>)
.MakeGenericType(e.Instance.GetType());
e.Instance.Logger = e.Context.Resolve(type);
});
Another workaround, that you may find cleaner is to inject an ILogger<T> with the same type as the type of the parent type:
public class Consumer : IConsumer
{
public Consumer(ILogger<Consumer> logger) { }
}
This makes the configuration much easier and prevents you from having to have a base class. Which one is most appropriate is up to you.
As I said, these are workarounds, but to be honest, you might need to reconsider your logging strategy in your application. Perhaps you are logging at too many places. In the applications I write there is hardly ever a need to log, and when I do, I write an logging message that is expressive enough so that there is no need to communicate the type that triggered the event. And when you log exception, you will always have a complete stack trace (and exception logging should almost only happen in the outer layer of your application and not within services anyway).
The following technique works well in our experience:
Create an attribute like below, which can be applied at class level or at the injection site:
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)]
public class LoggerAttribute : Attribute
{
public readonly string Name;
public LoggerAttribute(string name)
{
Name = name;
}
}
Create an Autofac module that you register with the ContainerBuilder:
public class LogInjectionModule : Module
{
protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
}
static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var typePreparing = e.Component.Activator.LimitType;
// By default, the name supplied to the logging instance is the name of the type in which it is being injected into.
string loggerName = typePreparing.FullName;
//If there is a class-level logger attribute, then promote its supplied name value instead as the logger name to use.
var loggerAttribute = (LoggerAttribute)typePreparing.GetCustomAttributes(typeof(LoggerAttribute), true).FirstOrDefault();
if (loggerAttribute != null)
{
loggerName = loggerAttribute.Name;
}
e.Parameters = e.Parameters.Union(new Parameter[]
{
new ResolvedParameter(
(p, i) => p.ParameterType == typeof (Logger),
(p, i) =>
{
// If the parameter being injected has its own logger attribute, then promote its name value instead as the logger name to use.
loggerAttribute = (LoggerAttribute)
p.GetCustomAttributes(typeof(LoggerAttribute),true).FirstOrDefault();
if (loggerAttribute != null)
{
loggerName = loggerAttribute.Name;
}
// Return a new Logger instance for injection, parameterised with the most appropriate name which we have determined above.
return LogManager.GetLogger(loggerName);
}),
// Always make an unamed instance of Logger available for use in delegate-based registration e.g.: Register((c,p) => new Foo(p.TypedAs<Logger>())
new TypedParameter(typeof(Logger), LogManager.GetLogger(loggerName))
});
}
}
You can now inject a named Logger in any one of these ways depending on individual scenarios:
By default, the injected logger name will be given the full type name of the class it is injected into:
public class Foo
{
public Foo(Logger logger)
{
}
}
Use a constructor parameter [Logger] attribute to override the logger name:
public class Foo
{
public Foo([Logger("Meaningful Name")]Logger logger)
{
}
}
Use a class-level [Logger] attribute to set the same logger name override for all constructor overloads:
[Logger("Meaningful Name")]
public class Foo
{
public Foo(Logger logger, int something)
{
}
public Foo(Logger logger, int something, DateTime somethingElse)
{
}
}
Use constructor parameter [Logger] attributes on each constructor overload to set different logger names depending on the context of how you were constructed:
public class Foo
{
public Foo(Logger("Meaningful Name")]Logger logger, int something)
{
}
public Foo(Logger("Different Name")]Logger logger, int something, DateTime somethingElse)
{
}
}
IMPORTANT NOTE: If you register types to be resolved with logger constructor injection using Autofac's delegate registration, you MUST use the two parameter overload like so: Register((c,p) => new Foo(p.TypedAs<Logger>()).
Hope this helps!
It is possible to do this without generics.
However, please note that in Autofac 6.x, the resolution process has changed to use a resolve pipeline. This doesn't matter for most scenarios, but it does when you want to use the lifetime events like OnPreparing, etc. Most of the answers here on SO around overriding the Preparing event are very old and are now outdated. You can't override Preparing directly anymore.
There is an example on the Autofac documentation site doing this for log4net, and it works with NLog with only minor changes. Here is the basic idea:
public class Log4NetMiddleware : IResolveMiddleware
{
public PipelinePhase Phase => PipelinePhase.ParameterSelection;
public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> next)
{
// Add our parameters.
context.ChangeParameters(context.Parameters.Union(
new[]
{
new ResolvedParameter(
(p, i) => p.ParameterType == typeof(ILog),
(p, i) => LogManager.GetLogger(p.Member.DeclaringType)
),
}));
// Continue the resolve.
next(context);
// Has an instance been activated?
if (context.NewInstanceActivated)
{
var instanceType = context.Instance.GetType();
// Get all the injectable properties to set.
// If you wanted to ensure the properties were only UNSET properties,
// here's where you'd do it.
var properties = instanceType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);
// Set the properties located.
foreach (var propToSet in properties)
{
propToSet.SetValue(context.Instance, LogManager.GetLogger(instanceType), null);
}
}
}
}
Please also note that you have to understand how middleware works in Autofac. The documentation is a good place to start.

Castle Windsor Typed Factory Weirdness

I'm getting some very unexpected (I think) behavior with the Typed Factory facility. Basically, it's reusing transient component instances for constructor injection with Func<T>.
Here is the gist of it:
// this guy is registered as service EntityFrameworkRepositoryProvider, not IRepository
[Transient]
public class EntityFrameworkRepositoryProvider : IRepository
{
public EntityFrameworkRepositoryProvider(ObjectContext objectContext, Assembly assembly)
{
// HOLY MOLY BATMAN!! Every time I hit this constructor when getProvider gets called,
// I don't actually get the arguments passed into getProvider. I get the
// arguments that were passed into getProvider the very FIRST time
// it was called...in other words I get the wrong
// ObjectContext (for the wrong connection string)...BIG PROBLEM
// do stuff...
}
}
[Singleton]
// this guy gets registered on startup
internal class EntityFrameworkRepositoryProviderFactory : IRepositoryProviderFactory
{
private readonly Func<ObjectContext, Assembly, EntityFrameworkRepositoryProvider> getProvider;
public EntityFrameworkRepositoryProviderFactory(Func<ObjectContext, Assembly, EntityFrameworkRepositoryProvider> getProvider)
{
this.getProvider = getProvider;
// do stuff...
}
public IRepository CreateRepository()
{
var provider = getProvider(new ObjectContext(GetConnectionString()),
Assembly.GetExecutingAssembly);
// do stuff...
}
public string GetConnectionString()
{
// returns one of a few diff EF connection strings
}
}
I also have a standard LazyComponentLoader. What am I doing wrong here? What should I do instead?
Thanks.
Problem was this seemingly harmless code in the LazyComponentLoader:
public IRegistration Load(string key, Type service, IDictionary arguments)
{
var component = Component.For(service);
if (!string.IsNullOrEmtpy(key))
{
component = component.Named(key);
}
if (arguments != null)
{
// This makes the typed factory facility screw up. (Merge is an extension method that merges dictionaries)
component.DynamicParameters((k, d) => d.Merge(arguments));
}
return component;
}
public static void Merge(this IDictionary target, IDictionary source)
{
foreach (object key in source.Keys)
{
target[key] = source[key];
}
}

How to use methods in ObjectContext class, if I use IObjectSet<T> for unit test?

I am using EF4 with POCO and trying to make it testable architecture.
So I create IObjectContext interface as follow :
public interface IObjectContext
{
IObjectSet<Employee> Employees { get; }
IObjectSet<Team> Teams { get; }
void Commit();
}
Then I changed type of properties to IObjectSet in my real ObjectContext class as follow :
public partial class HRManagementEntities : ObjectContext, IUnitOfWork
{
// skip some codes here...........
public IObjectSet<Employee> Employees
{
get { return _employees ?? (_employees = CreateObjectSet<Employee>("Employees"));
}
private IObjectSet<Employee> _employees;
public IObjectSet<Team> Teams
{
get { return _teams ?? (_teams = CreateObjectSet<Team>("Teams")); }
}
private IObjectSet<Team> _teams;
public void Commit()
{
SaveChanges();
}
}
In my service layer, consume EF like this :
public class Service
{
private IObjectContext ctx;
public HRService(IObjectContext ctx)
{
this.ctx = ctx;
}
public List<Team> GetAllTeams()
{
return ctx.Teams.ToList();
}
}
Here is my problem, How to call methods in ObjectContext for example, ApplyCurrentValues(), ExecuteStoreCommand(), and so on... ?
Do I need to implement those methods in the IObjectContext to use?
EDIT
As RPM's advice, I created following extension method for ApplyCurrentValues() method, another methods could be extended in same way.
public static T UpdateModel<T>(this IObjectSet<T> iObjectSet, T currentEntity) where T : class
{
ObjectSet<T> objectSet = iObjectSet as ObjectSet<T>;
if (objectSet == null || currentEntity == null)
throw new ArgumentNullException();
return objectSet.ApplyCurrentValues(currentEntity);
}
You need to create extension methods for the methods you need, and cast the IObjectSet to ObjectSet.
For instance, if you need to do .Include (eager loading), use this extension method:
public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
var objectQuery = source as ObjectQuery<TSource>;
if (objectQuery != null)
{
objectQuery.Include(path);
}
return source;
}
You could probably do the same thing for IObjectContext, but not sure why you are even mocking this out. You should not expose the OC to outside the repository, only the repository should know about the OC.
In your example, your service is calling ctx.Teams on the entities/repository.
IMO your service should be calling ctx.Find, which would be strongly-typed (via generics) to the Teams object context. (IRepository)
A common trap is to over-mock things. Don't mock everything just for the sake of it, mock the functionality which you require for unit testing.
If you want to abstract out the Object Context then use the Unit of Work pattern.

Resources