Spring.net is not looking for definition in the parent container - spring.net

In my project I have 2 configurations for spring, one in code and one in xml. The code context will load the mock objects defined in the MockConfigurations class. The xml config is defined in the app.config. I’m setting the xml config as parent of the code config.
public static IApplicationContext GetMergedContainer()
{
var scanner = new AssemblyObjectDefinitionScanner();
scanner.IncludeType<MockConfigurations>();
var context = new CodeConfigApplicationContext(ContextRegistry.GetContext());
context.Scan(scanner);
context.Refresh();
return context;
}
In the spring documentation (http://www.springframework.net/doc-latest/reference/html/web.html) it says:
If a referenced object definition is not found in the current context, Spring.NET searches all ancestor contexts in the context hierarchy until it finds the object definition (or ultimately fails and throws an exception).
That is not working for me:
var element = GetMergedContainer().GetObject<IElement>();
throws Spring.Objects.Factory.NoSuchObjectDefinitionException : No object named '[Namespace].IElement' is defined : Requested Type not Defined in the Context.
Whether the getting the object from the parent works fine:
var element = GetMergedContainer().ParentContext.GetObject<IElement>();
Am I missing something? Has anyone succeeded in setting an XML context as parent of a code context?
Any help will be appreciated.
Thanks in advance.
I’m using Spring.Core.1.3.2 and Spring.CodeConfig.1.0.4
[UPDATE]
I was recreating the situation with a more simple code (http://www.springframework.net/codeconfig/refdoc/migration-example.html)
I put again an XML config as parent of the code config and I tried to resolve an object from the code context that exists only in the XML (parent) context.
This works:
ConsoleReport report = ctx["ConsoleReport"] as ConsoleReport;
ConsoleReport report = ctx.GetObject("ConsoleReport") as ConsoleReport;
This fails:
ConsoleReport report = ctx.GetObject<ConsoleReport>();
The error is the following:
Spring.Objects.Factory.NoSuchObjectDefinitionException was unhandled
Message=No object named 'Spring.Evaluation.ConsoleReport' is defined : Requested Type not >Defined in the Context.
Source=Spring.Core.Configuration
ObjectName=Spring.Evaluation.ConsoleReport
StackTrace:
at Spring.Context.ApplicationContextExtensions.GetObject[T](IApplicationContext
context) in c:_prj\spring-net-codeconfig\src\Spring.Core.Configuration\Context\Extension\ApplicationContextExtensions.cs:line 69
at Spring.Evaluation.Program.Main(String[] args) in c:\users\oscar\documents\visual studio 2010\Projects\Spring.Evaluation\Spring.Evaluation\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,
ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I’m trying to add the code configuration to a project (a little big) that uses the later approach, and I would very much like to maintain all those lines of codes as they are.

Related

Entity Framework Core Adding New Migration After Initial Creation

I have ASP.Net Core project and as ORM, it's based on Entity Framework Core version 3.1.8. It can be migrated and updated for first initial creation from CLor Package Manager Console, no worries. The problem is when I add a new table or a new property for existing entity, it's unable to add new migration. Exception details are below.
PM> dotnet ef migrations add "newone"
Build started...
Build succeeded.
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.EntityFrameworkCore.Update.Internal.SharedTableEntryMap1.GetMainEntry(IUpdateEntry entry) at Microsoft.EntityFrameworkCore.Update.Internal.SharedTableEntryMap1.GetOrAddValue(IUpdateEntry entry)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffData(TableMapping source, TableMapping target, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Diff(TableMapping source, TableMapping target, DiffContext diffContext)+MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.DiffCollection[T](IEnumerable1 sources, IEnumerable1 targets, DiffContext diffContext, Func4 diff, Func3 add, Func3 remove, Func4[] predicates)+MoveNext()
at System.Linq.Enumerable.ConcatIterator1.MoveNext() at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IModel source, IModel target)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.
Also my DbContext & DbContextFactory code snippets are below
//My DbContextFactory CreateDbContext Method
public DataContext CreateDbContext(string[] args)
{
var env = GetEnvironment();
var connectionStr = SetDatabaseConnectionString(env);
var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable(connectionStr, EnvironmentVariableTarget.Machine));
optionsBuilder.EnableSensitiveDataLogging();
return new DataContext(optionsBuilder.Options, null);
}
//My DbContext Constructor
public DataContext(DbContextOptions<DataContext> options, IHttpContextAccessor httpContextAccessor) : base(options)
{
_logger = LogManager.GetCurrentClassLogger();
_logger.Info("Domain User : SYSTEM Details : DataContext initialized");
Database?.SetCommandTimeout(5000);//TODO : fetch from config
_httpContextAccessor = httpContextAccessor;
}
After lots of staff the problem is solved. It was, there is navigation property exists in entity but relation was not defined. After trying to add a new migration, null object reference exception was thrown but no details! I debugged all migration class, and at last realized the null object was the relation. I just advice if you face any kind of migration problem, comment all poco entities and check all entity navigations and relations step by step to find the problem.

Scope gets lost in Castle Windsor typed factory?

I have following Windsor component registration code in a container with TypedFactoryFacility:
Component
.For<IMyItemFactory>()
.AsFactory(f => f.SelectedWith(new MyComponentSelector()))
.LifestylePerWcfOperation(),
Classes
.FromAssembly(Assembly.GetExecutingAssembly())
.BasedOn<IMyItem>()
.LifestylePerWcfOperation()
.Configure(c => c.Named(c.Implementation.Name)),
that strives to create autoimplementation of IMyItemFactory. During execution of IMyItemFactory factory method program fails with exception
Castle.MicroKernel.ComponentResolutionException: Could not obtain scope for component SpecificItem. This is most likely either a bug in custom IScopeAccessor or you're trying to access scoped component outside of the scope (like a per-web-request component outside of web request etc)
at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.GetScope(CreationContext context)
at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)
at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(String key, Type service, IDictionary arguments, IReleasePolicy policy)
at Castle.Facilities.TypedFactory.TypedFactoryComponentResolver.Resolve(IKernelInternal kernel, IReleasePolicy scope)
at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Resolve(IInvocation invocation)
at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IMyItemFactoryProxy.GetMyItem(String myItemType)
It's confusing as practically every component in the application has WcfOperation scope, so I don't understand how this can happen. I even try to log every registered type with its scope to assert that IMyItem classes have WcfOperation scope – and they have.
Do you have any idea how to debug this?
Edit: I am calling the factory from successfully constructed object with WcfOperation-scope that calls another WcfOperation-scoped services without a problem:
public SomeDataProvider(IElasticsearchClient elasticClient, IMyItemFactory factory)
{
_elasticClient = elasticClient;
_factory = factory;
}
async Task SomeMethod()
{
var someString = await _elasticClient.SomeMethod(); // ok
var myItem = _factory.GetMyItem(someString); // exception from above
// ...
}
As mentioned in the comments OperationContext.Current was null so technically Windsor was doing the right thing - alerting you to the fact.

Unity and Random "Index was outside the bounds of the array" exception

We are running web site with around 15.000 realtime user (google analytics) (Around 1000 request/sec (perf counters)).
We have two web server behind load balancer.
Sometimes every day sometimes 1 time in a week one of our web servers stop execute requests and start to response with error and every request is logging following exception:
"System.IndexOutOfRangeException - Index was outside the bounds of the array."
Our environment : IIS 8.5, .Net 4.5.0, Mvc 5.1.0, Unity 3.5 (same state with 3.0), WebActivatorEx 2.0
In IIS, Worker Process 1 and other settings are with defaults.
We could not catch any specific scenario made this error. After App pool recycle everything start with no problem. And before every request respond with error, there is not any error related with it.
There is one question asked in the past with related old Unity version:
https://unity.codeplex.com/discussions/328841
http://unity.codeplex.com/workitem/11791
Could not see anything I can do about it.
Here exception details:
System.IndexOutOfRangeException
Index was outside the bounds of the array.
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.Practices.Unity.NamedTypesRegistry.RegisterType(Type t, String name)
at Microsoft.Practices.Unity.UnityDefaultBehaviorExtension.OnRegisterInstance(Object sender, RegisterInstanceEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Microsoft.Practices.Unity.UnityContainer.RegisterInstance(Type t, String name, Object instance, LifetimeManager lifetime)
at Microsoft.Practices.Unity.UnityContainerExtensions.RegisterInstance[TInterface](IUnityContainer container, TInterface instance, LifetimeManager lifetimeManager)
at DemoSite.News.Portal.UI.App_Start.UnityConfig.<>c__DisplayClass1.<RegisterTypes>b__0()
at DemoSite.News.Portal.Core.Controller.BaseController.Initialize(RequestContext requestContext)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
My configuration is as follows:
public static void RegisterTypes(IUnityContainer container)
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
container.LoadConfiguration(section);
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
}
Initialize method as follow:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
if (requestContext.RouteData.Values["ViewActionId"] != null)
{
int viewActionId;
if (!int.TryParse(requestContext.RouteData.Values["ViewActionId"].ToString(), out viewActionId))
return;
var cacheProvider = ServiceLocator.Current.GetInstance<ICacheProvider>();
List<ViewActionClass> viewActionClasses = null;
string cacheKey = CacheKeyCompute.ComputeCacheKey("ViewActionClass", CacheKeyTypes.DataCache,
new KeyValuePair<string, string>("viewActionId", viewActionId.ToString()));
_configuration = ServiceLocator.Current.GetInstance<IConfiguration>();
viewActionClasses =
cacheProvider.AddOrGetExistingWithLock<List<ViewActionClass>>(cacheKey, () =>
{
var viewActionClassBusiness =
ServiceLocator.Current.GetInstance<IViewActionClassBusiness>();
return viewActionClassBusiness.ViewActionClassGetByViewActionId(viewActionId);
});
ViewBag.ActionClass = viewActionClasses;
ViewBag.Configuration = _configuration;
}
base.Initialize(requestContext);
}
Registration xml for ICacheProvider, IConfiguration and IViewActionClassBusiness
<type type="DemoSite.Runtime.Caching.ICacheProvider, DemoSite.Core"
mapTo="DemoSite.Runtime.Caching.ObjectCacheProvider, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.Core.Configuration.IConfiguration, DemoSite.Core"
mapTo="DemoSite.Core.Configuration.ConfigFileConfiguration, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.News.Business.IViewActionClassBusiness, DemoSite.News.Business"
mapTo="DemoSite.News.Business.Default.ViewActionClassBusiness, DemoSite.News.Business.Default">
<lifetime type="perRequestLifetimeManager" />
</type>
Maybe it is related with high traffic.
Is there anyone encounter a problem like that and any solution ?
Thanks in advance
As far as I can see from the stack trace you are registering instances in the container during the web request. The RegisterType and RegisterInstance methods are not thread-safe in Unity (and this probably holds for most DI libraries in .NET). This explains why this is happening to at random points and under high load.
It is good practice to register your container only at start-up and don't change it later on. With the Dependency Inversion Principle and Dependency Injection pattern in particular you try to centralize the knowledge of how object graphs are wired, but you are decentralizing it again by doing new registrations later on. And even if registration was thread-safe with Unity, it's still very likely that you introduce race conditions by changing registrations during runtime.
UPDATE
Your code has the following code that causes the problems:
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
This seems very innocent, but in fact it causes both a concurrency bug and a memory leak.
Because the new statement is inside the lambda, it will cause a new UnityServiceLocator to be created every time you call ServiceLocator.Current. That wouldn't be bad by itself, but the UnityServiceLocator's constructor makes a call to container.RegisterInstance to register itself in the container. But as I already said: calling RegisterInstance` is not thread-safe.
But even if it was thread-safe, it still causes a memory leak in your application, since a call to RegisterInstance will not replace an existing registration, but appends it to a list of registrations. This means that the list of UnityServiceLocator instances in the container will keep growing and will eventually cause the system to crash with an OutOfMemoryException. You are actually lucky that you hit this concurrency bug first, because the OOM bug would be much harder to trace back.
The fix is actually very simple: move the construction of the UnityServiceLocator out of the lambda and return that single instance every time:
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
The behavior of the UnityServiceLocator is a design flaw in my opinion, because since RegisterInstance is not thread-safe and the UnityServiceLocator has no idea how many times it is created, it should never call RegisterInstance from within its constructor -or at least- not without doing a check whether it is safe to register that instance.
Problem however is that removing that call to RegisterInstance is a breaking change, but still probably the best solution for the Unity team. Most users will probably not notice the missing IServiceLocator registration anyway and if they do, Unity will communicate a clear exception message in that case. Another option would be to let the UnityServiceLocator check whether any instances have already been resolved from the container, and in that case throw an InvalidOperationException from within the UnityServiceLocator's constructor.

Why are my controllers being instantiated when they're not being called?

Here are the symptoms I am experiencing:
I have a brand new empty controller in an area:
public class JamController : Controller
{
public JamController()
{
throw new Exception("Not implemented!");
}
If I visit http://myprojectserver.example.com:12345/urlthatdoesnotexist, I get the following error:
[CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Not implemented!
Resulting in: An exception occurred while trying to create an instance of type 'MyWebProject.Areas.Users.Controllers.JamController'.
Resulting in: Cannot activate part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController --> MyWebProject.Areas.Users.Controllers.JamController
Resulting in: Cannot get export 'MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")' from part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")
]
System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +55
System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart) +78
System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +47
System.ComponentModel.Composition.Primitives.Export.get_Value() +57
System.ComponentModel.Composition.ExportServices.GetCastedExportedValue(Export export) +40
System.ComponentModel.Composition.<>c__DisplayClassa`1.<CreateStronglyTypedLazyOfT>b__6() +39
System.Lazy`1.CreateValue() +416
System.Lazy`1.LazyInitValue() +382
System.Lazy`1.get_Value() +75
MefContrib.Web.Mvc.<>c__DisplayClass4.<GetControllerType>b__0(Lazy`1 e) +53
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +204
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MefContrib.Web.Mvc.CompositionControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) +412
System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) +61
System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) +122
System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) +33
System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) +10
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +9709884
System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +699
My question is "Why?" Why on earth is it trying to instantiate this controller? Where do I look to determine what is causing this. I'm pretty sure it isn't expected behaviour to instantiate every controller on "page not found".
I'm at a loss to know where to look. Can someone point me in the direction of something that will help?
UPDATE:
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
This is down to a bug in MefContrib.Web.Mvc. This assembly implements it's own ControllerFactory that inherits from DefaultControllerFactory.
The factory overrides GetControllerType, I assume to try and resolve controllers that live in assemblies somewhere other than the default application or it's references. The implementation of GetControllerType first calls into base.GetControllerType to see if Defaultcontroller can resolve it.
If it can't - which is the case for urls that don't exist - it asks MEF for all exports that implement IController. This returns an IEnumerable<Lazy<IController>> with one item for every class that implements IController in the bin/ folder (by default).
It then runs a linq query over the IEnumerable, calling GetType() on the Value property of each Lazy<IController>. Requesting the Value of a Lazy<T> forces the instance to be created. This is why every controller in the bin/ is being constructed for a page that doesn't exist.
I don't think this is an easy problem to fix properly as there is no way of getting the Type instance from Lazy<T>.Value without creating the value. However by removing the lines from AppStart_MefContribMVC3.cs that register the ControllerFactory with Asp.Net - you have effectively stopped using MefContrib.Web.Mvc's ControllerFactory and just used Asp.Net's DefaultControllerFactory instead.
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).

Carrying CreationContext.AdditionalArguments on Castle Windsor

I need to pass some arguments to a custom AbstractLifestyleManager derived type.
When I request an instance of a type from the container, I use the following overload:
T Resolve<T>(string key, object argumentsAsAnonymousType)
For example:
public IHttpController CreateController(HttpControllerContext controllerContext, string controllerName)
{
var controller = this.container.Resolve<IHttpController>(
controllerName,
new { requestProperties = controllerContext.Request.Properties });
// ...
}
Then, inside the custom AbstractLifestyleManager derived type, I can do this:
var messageProperties = (IDictionary<string, object>)
context.AdditionalArguments["requestProperties"];
Which returns the value that I have previsouly passed.
However, if I call base.Resolve(context, releasePolicy) the AdditionalArguments is null if the code enters the custom type recursively.
Is it possible to pass/flow the AdditionalArguments between the base.Resolve calls?
I am not quite sure how the flow is, when implementing a lifestyle manager, but it sounds like the problem that CreateContext AdditionalArguments aren't propagated to child context per default. See this other question.
If that is the case, you could try to change the default as described in the linked question by subclassing DefaultDependencyResolver.

Resources