For some reason this:
[Transaction]
public void DoSomething()
{
...
}
does not work I still have to explicitly use the transaction like this:
public void DoSomething()
{
using (var tx = NHibernateSession.Current.BeginTransaction())
{
....
tx.Commit();
}
}
Any ideas why?
I am using something like this to bootstrap stuff:
_container = new WindsorContainer();
ComponentRegistrar.AddComponentsTo(_container);
...
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_container));
ComponentRegistrar.AddComponentsTo(_container, typeof(NHibernateTransactionManager));
NHibernateSession.Init(new ThreadSessionStorage(),
new[] { "Bla.Domain.dll" },
new AutoPersistenceModelGenerator().Generate(),
"NHibernate.config");
As Doan said the component that had the method is not proxied.
Since the method is not virtual, I am assuming that your class is implementing an interface. make sure that you have the dependency in the class calling DoSomething defined as the interface and not the implementing class.
if you debug the code, and check the run time type of the object, it should be a castle proxy
for more details check the trouble shooting section on Sharp Architecture contrib wiki
https://github.com/sharparchitecture/Sharp-Architecture-Contrib/wiki/Troubleshooting
Normally, this kind of problem is caused by the failure of invoking the dynamic proxy that provides the transaction management service. Two of the most common errors are:
The method cannot be proxied: most likely not implement any interface method, or the object was not proxied.
The method was called from the same class, which bypassed all proxies.
Edit:
I guess you use Castle Windsor as IoC container. The [Transaction] decoration requires the Automatic Transaction Management Facility in order to work. If you successfully configured the facility, i.e. you made [Transaction] work in one method, but not other, then the answer above applies. If all Transaction decoration failed to work, then you have to review the configuration of the facility first.
Related
I use FluentValidation in my project in order to validate almost every requests coming into my WebApi.
It works fine, but I've been asked to translate property names in the error messages. My projet must handle at least french and english, so for example, what I want to achieve is :
'First Name' is required (english case)
'Prénom' est requis (french case)
I already have a IPropertyLabelService for other purposes, that is injected in the Startup.cs, that I want to use. It finds translations of property names in a .json, which already works fine.
My problem is that I don't know how to use it globally. I know that FluentValidation's doc says to set the ValidatorOptions.DisplayNameResolver in the Startup file, like this :
FluentValidation.ValidatorOptions.DisplayNameResolver = (type, memberInfo, expression) => {
// Do something
};
I don't know how I can use my IPropertyLabelService inside this, as the Startup.ConfigureServices method is not over yet, so I can't resolve my service...
Any other solution to achieve this behaviour is also more than welcome. I considered using .WithMessage() or .WithName() but I have a really big amount of validators, that would be really long to add this to all individually.
I answered this over on the FluentValidation issue tracker, but for completeness will include the answer here too:
Ssetting FluentValidation.ValidatorOptions.Global.DisplayNameResolver is the correct way to handle this globally (or you can use WithName at the individual rule level).
You need to ensure that this is set once, globally. If you need the service provider to have been initialized first, then make sure you call it at a point after the service provider has been configured (but ensure you still only set it once).
The "options" configuration mechanism in .NET Core allows you to defer configuration until after the point services have been constructed, so you can create a class that implements IConfigureOptions, which will be instantiated and executed during the configuration phase for a particular options type. FluentValidation doesn't provide any options configuration itself, so you can just hook into one of the built-in options classes (ASP.NET's MvcOptions is probably the simplest, but you can also use a different one if you're not using mvc).
For example, you could do something like this inside your ConfigureServices method:
public void ConfigureServices(IServiceCollection services) {
// ... your normal configuration ...
services.AddMvc().AddFluentValidation();
// Afterwards define some deferred configuration:
services.AddSingleton<IConfigureOptions<MvcOptions>, DeferredConfiguration>();
}
// And here's the configuration class. You can inject any services you need in its constructor as with any other DI-enabled service. Make sure your IPropertyLabelService is registered as a singleton.
public class DeferredConfiguration : IConfigureOptions<MvcOptions> {
private IPropertyLabelService _labelService;
public DeferredConfiguration(IPropertyLabelService labelService) {
_labelService = labelService;
}
public void Configure(MvcOptions options) {
FluentValidation.ValidatorOptions.Global.DisplayNameResolver = (type, memberInfo, expression) => {
return _labelService.GetPropertyOrWhatever(memberInfo.Name);
};
}
}
I have a WebAPI service using SimpleInjector. I have this set up using AsyncScopedLifestyle for my scoped dependencies, and one of these dependencies is my Entity Framework DataContext. Many things in my service depend on the DataContext, and it is generally injected in to my MediatR handlers using constructor injection - this works well. Separately I have a few areas where I need to create an instance of an object given its type (as a string), so I have created a custom activator class (ResolvingActivator) that is configured with a reference to Container.GetInstance(Type):
In my container bootstrap code:
ResolvingActivator.Configure(container.GetInstance);
I can then create objects by using methods such as:
ResolvingActivator.CreateInstance<T>(typeName)
When I'm using WebAPI, the above is working perfectly.
A further part of the project is a legacy API that uses WCF. I have implemented this as a translation layer, where I translate old message formats to new message formats and then dispatch the messages to the Mediator; I then translate the responses (in new format) back to old format and return those to the caller. Because I need access to the Mediator in my WCF services, I'm injecting this in their constructors, and using the SimpleInjector.Integration.Wcf package to let SimpleInjector's supplied SimpleInjectorServiceHostFactory build instances of the services. I've also created a hybrid lifestyle, so I can use the same container for my both my WebAPI and WCF services:
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
new AsyncScopedLifestyle(),
new WcfOperationLifestyle());
This works well for some calls, but when a call ultimately calls my ResolvingActivator class, I get an ActivationException thrown, with the following message:
The DataContext is registered as 'Hybrid Async Scoped / WCF Operation' lifestyle, but the instance is requested outside the context of an active (Hybrid Async Scoped / WCF Operation) scope.
As I only receive this error when making WCF calls, I'm wondering if I have something wrong in my configuration. In a nutshell, this will work:
public class SomeClass
{
private readonly DataContext db;
public SomeClass(DataContext db)
{
this.db = db;
}
public bool SomeMethod() => this.db.Table.Any();
}
But this will not:
public class SomeClass
{
public bool SomeMethod()
{
// Code behind is calling container.GetInstance(typeof(DataContext))
var db = ResolvingActivator.CreateInstance<DataContext>();
return db.Table.Any();
}
}
Any ideas where I'm going wrong?
Edit: here is the stack trace from the ActivationException:
at SimpleInjector.Scope.GetScopelessInstance[TImplementation](ScopedRegistration`1 registration)
at SimpleInjector.Scope.GetInstance[TImplementation](ScopedRegistration`1 registration, Scope scope)
at SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope)
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.Container.GetInstance(Type serviceType)
at Service.Core.ResolvingActivator.CreateInstance(Type type) in Service.Core\ResolvingActivator.cs:line 43
at Service.Core.ResolvingActivator.CreateInstance(String typeName) in Service.Core\ResolvingActivator.cs:line 35
at Service.Core.ResolvingActivator.CreateInstance[TService](String typeName) in Service.Core\ResolvingActivator.cs:line 69
With a full stack trace here: https://pastebin.com/0WkyHGKv
After close inspection of the stack trace, I can conclude what's going on: async.
The WcfOperationLifestyle under the covers depends on WCF's OperationContext.Current property, but this property has a thread-affinity and doesn't flow with async operations. This is something that has to be fixed in the integration library for Simple Injector; it simply doesn't support async at the moment.
Instead, wrap a decorator around your handlers that start and end a new async scope. This prevents you from having to use the WcfOperationLifestyle all together. Take a look at the ThreadScopedCommandHandlerProxy<T> implementation here to get an idea how to do this (but use AsyncScopedLifestyle instead).
i'm using EasyNetQ library in my project and I would like to use Ninject as IoC Container for EasyNetQ components.
I created a custom logger in order to log anythong from EasyNetQ:
public class LogNothingLogger : IEasyNetQLogger
{
...
}
And then using the Ninject extension in my main function:
public class Program
{
static void Main(string[] args)
{
// Container creation and custom logger registration
IKernel cointainer = new StandardKernel();
cointainer.Bind<IEasyNetQLogger>().To<LogNothingLogger>();
// Register Ninject as IoC Container for EasyNetQ
cointainer.RegisterAsEasyNetQContainerFactory();
// Create bus
using (IBus bus = RabbitHutch.CreateBus("host=localhost"))
{
// Do something with bus...
}
}
}
But I get the following exception:
Ninject.ActivationException was unhandled
More than one matching bindings are available.
Matching bindings:
1) binding from IEasyNetQLogger to LogNothingLogger
2) binding from IEasyNetQLogger to method
Activation path:
2) Injection of dependency IEasyNetQLogger into parameter logger of constructor of type RabbitBus
1) Request for RabbitBus
Suggestions:
1) Ensure that you have defined a binding for IEasyNetQLogger only once.
[...]
Am I using this package in the wrong way? Is there any solution?
Thanks!
As the exception says, there are two bindings for IEasyNetQLogger.
I suppose that an ninject extension you are using is already binding an IEasyNetQLogger.
You could use Rebind (IBindingRoot.Rebind<IEasyNetQLogger>()) to override any existing binding for IEasyNetQLogger.
But i would also advise you to look into why the extension is already creating a binding and how it is supposed to be used.
What is the extension you are using?
Edit: i took a glance at https://github.com/mikehadlow/EasyNetQ/tree/master/Source/EasyNetQ.DI.Ninject
and i did not find any binding for IEasyNetQLogger. Are you sure you don't have defined an additional IBindingRoot.Bind<IEasyNetQLogger>().ToMethod(...) binding?
It could also be NinjectAdapter.Register<IEasyNetQLogger>(Func<IEasyNetQLogger> ...).
If you have not done so, then the EasyNetQ is already registering a logger by NinjectAdapter.Register<IEasyNetQLogger>(Func<IEasyNetQLogger> ...).
As before, you can use Rebind(..) to replace the binding (which must be done after the original binding was created!) or look into how it is supposed to work.
Of course you might also just want to skip the binding since you only created one for "log nothing logger"...
Problem (abstract)
Given a module which registers dependency X. The dependency X has a different lifetime in a MVC3 app (lifetime per HttpRequest) then in a console application (dependency per lifetimescope with a name). Where or how to specify the lifetime of dependency X?
Case
I've put all my database related code in a assembly with a module in it which registers all repositories. Now the ISession (Nhibernate) registration is also in the module.
ISession is dependency X (in the given problem case). ISession has different lifetime in a MVC3 app (lifetime per request) then in a console app where I define a named lifetimescope.
Should the registration of ISession be outside the module? Would be strange since it's an implementation detail.
What is the best case to do here? Design flaw or are there smart constructions for this :) ?
Given your use case description, I'd say you have a few of options.
First, you could just have each application register their own set of dependencies including lifetime scope. Having one or two "duplicate" pieces of code in this respect isn't that big of a deal considering the differences between the application and the fact that the registrations appear fairly small.
Second, you could wrap the common part (minus lifetime scope) into a ContainerBuilder extension method that could be used in each application. It would still mean each app has a little "duplicate code" but the common logic would be wrapped in a simple extension.
public static IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>
RegisterConnection<TLimit, ScanningActivatorData, DynamicRegistrationStyle>(this ContainerBuilder builder)
{
// Put the common logic here:
builder.Register(...).AsImplementedInterfaces();
}
Consuming such an extension in each app would look like:
builder.RegisterConnection().InstancePerHttpRequest();
// or
builder.RegisterConnection().InstancePerLifetimeScope();
Finally, if you know it's either web or non-web, you could make a custom module that handles the switch:
public class ConnectionModule : Autofac.Module
{
bool _isWeb;
public ConnectionModule(bool isWeb)
{
this._isWeb = isWeb;
}
protected override void Load(ContainerBuilder builder)
{
var reg = builder.Register(...).AsImplementedInterfaces();
if(this._isWeb)
{
reg.InstancePerHttpRequest();
}
else
{
reg.InstancePerLifetimeScope();
}
}
}
In each application, you could then register the module:
// Web application:
builder.RegisterModule(new ConnectionModule(true));
// Non-web application:
builder.RegisterModule(new ConnectionModule(false));
Alternatively, you mentioned your lifetime scope in your other apps has a name. You could make your module take the name:
public class ConnectionModule : Autofac.Module
{
object _scopeTag;
public ConnectionModule(object scopeTag)
{
this._scopeTag = scopeTag;
}
protected override void Load(ContainerBuilder builder)
{
var reg = builder.Register(...)
.AsImplementedInterfaces()
.InstancePerMatchingLifetimeScope(this._scopeTag);
}
}
Consumption is similar:
// Web application (using the standard tag normally provided):
builder.RegisterModule(new ConnectionModule("httpRequest"));
// Non-web application (using your custom scope name):
builder.RegisterModule(new ConnectionModule("yourOtherScopeName"));
I would recommend against simply using InstancePerLifetimeScope in a web application unless that's actually what you intend. As noted in other answers/comments, InstancePerHttpRequest uses a specific named lifetime scope so that it's safe to create child lifetime scopes; using InstancePerLifetimeScope doesn't have such a restriction so you'll actually get one connection per child scope rather than one connection for the request. I, personally, don't assume that other developers won't make use of child lifetime scopes (which is a recommended practice), so in my applications I'm very specific. If you're in total control of your application and you can assure that you aren't creating additional child scopes or that you actually do want one connection per scope, then maybe InstancePerLifetimeScope will solve your problem.
It's common practice to use a one connection per http request. That being the case, connections would be registered using .InstansePerLifetimeScope(). For example, you might do something like:
builder
.Register(c => {
var conn = new SqlConnection(GetConnectionString());
conn.Open();
return conn;
})
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
I'm working on a framework extension which handles dynamic injection using Ninject as the IoC container, but I'm having some trouble trying to work out how to achieve this.
The expectation of my framework is that you'll pass in the IModule(s) so it can easily be used in MVC, WebForms, etc. So I have the class structured like this:
public class NinjectFactory : IFactory, IDisposable {
readonly IKernel kernel;
public NinjectFactory(IModule[] modules) {
kernel = new StandardKernel(modules);
}
}
This is fine, I can create an instance in a Unit Test and pass in a basic implementation of IModule (using the build in InlineModule which seems to be recommended for testing).
The problem is that it's not until runtime that I know the type(s) I need to inject, and they are requested through the framework I'm extending, in a method like this:
public IInterface Create(Type neededType) {
}
And here's where I'm stumped, I'm not sure the best way to check->create (if required)->return, I have this so far:
public IInterface Create(Type neededType) {
if(!kernel.Components.Has(neededType)) {
kernel.Components.Connect(neededType, new StandardBindingFactory());
}
}
This adds it to the components collection, but I can't work out if it's created an instance or how I create an instance and pass in arguments for the .ctor.
Am I going about this the right way, or is Ninject not even meant to be be used that way?
Unless you want to alter or extend the internals of Ninject, you don't need to add anything to the Components collection on the kernel. To determine if a binding is available for a type, you can do something like this:
Type neededType = ...;
IKernel kernel = ...;
var registry = kernel.Components.Get<IBindingRegistry>();
if (registry.Has(neededType)) {
// Ninject can activate the type
}
Very very late answer but Microsoft.Practices.Unity allows Late Binding via App.Config
Just in case someone comes across this question