Coder Social home page Coder Social logo

castleproject / windsor Goto Github PK

View Code? Open in Web Editor NEW
1.5K 1.5K 456.0 101.62 MB

Castle Windsor is a best of breed, mature Inversion of Control container available for .NET

Home Page: http://www.castleproject.org

License: Apache License 2.0

C# 99.83% Batchfile 0.15% ASP.NET 0.02%

windsor's People

Contributors

aduckardt avatar anton-iermolenko avatar asgerhallas avatar asssssssssssssss avatar ayende avatar cneuwirt avatar drusellers avatar fabiob avatar flcdrg avatar fschmied avatar generik0 avatar haf avatar hammett avatar hconceicao avatar jevonius avatar jnm2 avatar jonorossi avatar joshrobb avatar kenegozi avatar kkozmic avatar leemhenson avatar mahara avatar mausch avatar mzywitza avatar rbellamy avatar roelofb avatar sellig avatar spicycode avatar tunatoksoz avatar whut avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

windsor's Issues

Bug - optional dependencies not provided

    public void Bug()
    {
        var container = new WindsorContainer();
        container.AddFacility<TypedFactoryFacility>();

        container.Register(Component.For<ISomeServiceToResolveLater>().ImplementedBy<SomeServiceToResolverLaterImpl>());
        container.Register(Component.For<ISomethingWithAFuncCtorDependency>().ImplementedBy<SomethingWithAFuncCtorDependency>());
        container.Register(Component.For<ClassWithOptionalDependency>());

        // this will make the test pass
        // container.Resolve<ISomethingWithAFuncCtorDependency>();

        var component = container.Resolve<ClassWithOptionalDependency>();

        Assert.That(component.Optional, Is.Not.Null);
    }

public class ClassWithOptionalDependency
{
    public ISomethingWithAFuncCtorDependency Optional { get; set; } 
}
public interface ISomeServiceToResolveLater
{

}
public class ISomethingWithAFuncCtorDependency
{

}
public class SomeServiceToResolverLaterImpl : ISomeServiceToResolveLater
{
     public SomeServiceToResolverLaterImpl(string giveMeThis)
     {

     }
}
public class SomethingWithAFuncCtorDependency : ISomethingWithAFuncCtorDependency
{
    private Func<string, ISomeServiceToResolveLater> _mandatory;

    public SomethingWithAFuncCtorDependency(Func<string, ISomeServiceToResolveLater> mandatory)
    {
        _mandatory = mandatory;
    }
}

Singleton not tracked

Hi,
I am using Castle.Windsor 3.2.0.0 strange issue on singletons. It used to work on version 2.x but I cannot find the problem for this version.

[Test]
public void Disposable_Singletons_are_tracked_for_disposal()
{
    IKernel k = new DefaultKernel();
    k.Register(Component.For<DisposableComponent>().LifestyleSingleton());

    var comp = k.Resolve<DisposableComponent>();
    Assert.IsTrue(k.ReleasePolicy.HasTrack(comp));
    GC.Collect();
    Assert.IsTrue(k.ReleasePolicy.HasTrack(comp));
}

So the default policy on Singletons are not tracked.

Also (same problem but different...)

[Test] 
public void Disposable_Singletons_are_tracked_for_disposal_for_custom_DoNotTrackTransientsReleasePolicy()
{
    IKernel k = new DefaultKernel();
    k.ReleasePolicy = new DoNotTrackTransientsReleasePolicy(null,null);
    k.Register(Component.For<DisposableComponent>().LifestyleSingleton());

    var comp = k.Resolve<DisposableComponent>();
    Assert.IsTrue(k.ReleasePolicy.HasTrack(comp));
    GC.Collect();
    Assert.IsTrue(k.ReleasePolicy.HasTrack(comp));
}

Where I have this custom policy life and the Track method dos not get called...It is called on Transient lifestyle but....:

public class DoNotTrackTransientsReleasePolicy : LifecycledComponentsReleasePolicy
{
    public DoNotTrackTransientsReleasePolicy(IKernel kernel) : base(kernel)
    {
    }

    public DoNotTrackTransientsReleasePolicy(ITrackedComponentsDiagnostic trackedComponentsDiagnostic, ITrackedComponentsPerformanceCounter trackedComponentsPerformanceCounter) : base(trackedComponentsDiagnostic, trackedComponentsPerformanceCounter)
    {
    }

    public override void Track(object instance, Burden burden)
    {
        if (burden.Model.LifestyleType == LifestyleType.Transient)
            return;

        base.Track(instance, burden);
    }
}

Thanks so much.

Child Container Not Disposing Services When It Is Disposed

I'm trying to use a childcontainer to manage a scope for Simple.Web, the expectation is that when I dispose the child container, it should dispose the referenced services.
But at the moment its not calling dispose on those services.

Discussion here:
https://groups.google.com/forum/?hl=en&fromgroups=#!topic/castle-project-users/ARMLev6jWnQ

Sample Code here:

  • The DisposesInstances() Test

https://github.com/mickdelaney/Simple.Web/blob/master/src/Simple.Web.Windsor.Tests/HandlerFactoryBuilderTests.cs

Child container fails in multi threaded environment

If you resolve a component from a child container it fails from to time if run in multi threaded environment.
The following works fine if executed in a single thread:

using (WindsorContainer childContainer = new WindsorContainer())
{
  container.AddChildContainer(childContainer);
  childContainer.Resolve(typeof(ICombined1));
}

If the code above is executed with several threads at the same time (sharing the base container), it sometimes throws an exception.

Here is the full code:

using System;
using System.Threading;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer();
            container.Register(Component.For<ISingleton1>().ImplementedBy<Singleton1>());
            container.Register(Component.For<ITransient1>().ImplementedBy<Transient1>().LifeStyle.Transient);
            container.Register(Component.For<ICombined1>().ImplementedBy<Combined1>().LifeStyle.Transient);

            // This works
            // TestChildController(container);

            // This fails sometimes
            TestChildControllerMultiThreaded(container);

            Console.ReadKey();
        }

        private static void TestChildControllerMultiThreaded(WindsorContainer container)
        {
            Thread[] threads = new[] 
            { 
                new Thread(() => TestChildController(container)),
                new Thread(() => TestChildController(container))
            };

            foreach (var thread in threads)
            {
                thread.Start();
            }

            foreach (var thread in threads)
            {
                thread.Join();
            }
        }

        private static void TestChildController(WindsorContainer container)
        {
            for (int i = 0; i < 500000; i++)
            {
                using (WindsorContainer childContainer = new WindsorContainer())
                {
                    try
                    {
                        container.AddChildContainer(childContainer);

                        childContainer.Resolve(typeof(ICombined1));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }

                if (i % 10000 == 0)
                {
                    Console.WriteLine(i);
                }
            }
        }
    }

    public interface ICombined1
    {
    }

    public class Combined1 : ICombined1
    {
        public Combined1(ISingleton1 first, ITransient1 second)
        {
            if (first == null)
            {
                throw new ArgumentNullException("first");
            }

            if (second == null)
            {
                throw new ArgumentNullException("second");
            }
        }
    }

    public interface ISingleton1
    {
    }

    public class Singleton1 : ISingleton1
    {
    }

    public interface ITransient1
    {
    }

    public class Transient1 : ITransient1
    {
    }
}

build NuGet and Zip packages from TeamCity

essentially the same as castleproject/Core#49:

Update the source and create a TeamCity build configuration ("Pack") to automatically build NuGet packages and a comprehensive Zip file for the Windsor projects.

I can take this. (Also, I thought I created this issue about 9 hours ago, but can't find it.)

WCF facility policy doesn't work when using async methods

When using BeginWcfCall(...) all the wcf policy that tries to catch exception doesn't work, I'm still investigating, but it seems the same problem that you can have in every async Interceptor, because of course if the function is async it will exit soon as the thread/task is created and fired. I had the same problem with the task programming, where I've fixed checking if the invocation.ReturnValue is a Task, and if yes, attach a continuation to do what was need it from the interception, in that case simple logging.

In the meanwhile I'm investigating the issue, and a possible solution, I would like to share with you a test console program, that shows the behavior:

using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using Castle.Facilities.WcfIntegration;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace TestClient
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.Write("Test sync (1 default) or async (2): ");
            var test = Console.ReadLine();

            var returnFaults = new ServiceDebugBehavior
            {
                IncludeExceptionDetailInFaults = true,
                HttpHelpPageEnabled = true
            };

            var serverContainer = new WindsorContainer()
                .AddFacility<WcfFacility>()
                .Register(
                    Component.For<IServiceBehavior>().Instance(returnFaults),
                    Component.For<ITestService>()
                             .ImplementedBy<TestService>()
                             .AsWcfService(new DefaultServiceModel()
                                               .AddBaseAddresses("http://localhost:4455")
                                               .PublishMetadata(mex => mex.EnableHttpGet())
                                               .AddEndpoints(WcfEndpoint
                                                                 .ForContract<ITestService>()
                                                                 .BoundTo(new BasicHttpBinding())))
                );

            var clientContainer = new WindsorContainer()
                .AddFacility<WcfFacility>()
                .Register(
                    Component.For<CatchAsyncPolicy>(),
                    Component.For<ITestService>()
                             .AsWcfClient(WcfEndpoint.ForContract<ITestService>()
                                                     .BoundTo(new BasicHttpBinding())
                                                     .At("http://localhost:4455"))
                );

            bool stopped = false;
            var testService = clientContainer.Resolve<ITestService>();
            var t = new Thread(() =>
            {
                while (!stopped)
                {
                    if (test == "2")
                    {
                        try
                        {
                            Console.WriteLine("Async Call: testService.BeginWcfCall(c => c.GetRandomValue(), call =>");
                            var ac = testService.BeginWcfCall(c => c.GetRandomValue(), call =>
                            {
                                try
                                {
                                    var rn = call.End();
                                    Console.WriteLine("Async Reply: random number: {0}", rn);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Async Error: {0}", e.Message);
                                }
                            }, null);

                            ac.AsyncWaitHandle.WaitOne();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("BeginWcfCall Error: {0}", ex.Message);
                        }
                    }
                    else
                    {
                        // test == "1"
                        try
                        {
                            Console.WriteLine("Call: testService.GetRandomValue()");
                            var rn = testService.GetRandomValue();
                            Console.WriteLine("Reply: random number: {0}", rn);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: {0}", ex.Message);
                        }
                    }

                    if (!stopped) Thread.Sleep(2000);
                }
            });
            t.Start();

            Console.WriteLine("Press enter to CLOSE the service...");
            Console.ReadLine();

            serverContainer.Dispose();

            Console.WriteLine("Press enter to exit the application...");
            Console.ReadLine();

            stopped = true;
            t.Join();

            clientContainer.Release(testService);
            clientContainer.Dispose();
        }
    }

    public class CatchAsyncPolicy : AbstractWcfPolicy
    {
        public override void Apply(WcfInvocation wcfInvocation)
        {
            var refresh = false;

            try
            {
                Console.WriteLine("Proceed: wcfInvocation.Refresh(false).Proceed()");
                wcfInvocation.Refresh(false).Proceed();
                //var result = invocation.ReturnValue;
                //var task = result as Task;
                //if (task != null)
                //{
                //}
            }
            catch (Exception ex) // Catch everything just for testing purpose
            {
                refresh = true;
                Console.WriteLine("Proceed Exception!");
            }

            if (refresh)
            {
                Console.WriteLine("Retry-Proceed: wcfInvocation.Refresh(true).Proceed()");
                wcfInvocation.Refresh(true).Proceed();
            }
        }
    }

    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        int GetRandomValue();

        [OperationContract]
        int MultiplyValues(int a, int b);

        [OperationContract]
        void Execute();
    }

    public class TestService : ITestService
    {
        public int GetRandomValue()
        {
            var random = new Random();
            return random.Next();
        }

        public int MultiplyValues(int a, int b)
        {
            return a * b;
        }

        public void Execute()
        {
            Trace.WriteLine("Call Execute()");
        }
    }
}

The test start and ask which kind of test would you like to run: 1 for sync, 2 for async.

After the start, you should see calls and replies, then press ENTER to close the service and simulate a failure of the endpoint.

If you run the test in sync, you will see that the CatchAsyncPolicy will catch the exception and retry the call. If you run the test in async, instead you will see that no retry is going on and no exception is catch by around proceed.

Castle.Core 3.3.0 does not contain any assembly references .NETCore,Version=v4.5.1'

When I try to install Castle Windsor on windows 8.1 VS 2013 I got the following error :

Could not install package 'Castle.Core 3.3.0'. You are trying to install this package into a project that targets '.NETCore,Version=v4.5.1', but the package does not contain any assembly references or
content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:2

  • Install-Package Castle.Windsor
  • CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
  • FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

WCFIntegrationFacility. I get an exception when moved ContractBehavior implementation into another assembly

I have assemblies
ProductService (refrences ProductService.Interfaces and Common.Interfaces)
ProductService.Interfaces (references Common.Interfaces)
Common.Interfaces

ProductService is ASP.NET project which exposes WCF services which are defined in ProductService.Interfaces

I've got this attibute.

    public class ArchiveSerializerContractBehaviorAttribute : Attribute, IContractBehavior
    {
...
    }

Initially that attribute was in the ProductService.Interfaces. Recently I needed to expose some services which are defined in Common.Interfaces and I have to mark interfaces in Common.Interfaces with that attribute. So I moved it to a Common.Interfaces assembly and as result I received this error:

Server Error in '/' Application.

The value could not be added to the collection, as the collection already contains an item of the same type: 'Common.Interfaces.Wcf.ArchiveSerializerContractBehaviorAttribute'. This collection only supports one instance of each type.
Parameter name: item 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.ArgumentException: The value could not be added to the collection, as the collection already contains an item of the same type: 'Common.Interfaces.Wcf.ArchiveSerializerContractBehaviorAttribute'. This collection only supports one instance of each type.
Parameter name: item

Source Error: 


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 



[ArgumentException: The value could not be added to the collection, as the collection already contains an item of the same type: 'Common.Interfaces.Wcf.ArchiveSerializerContractBehaviorAttribute'. This collection only supports one instance of each type.
Parameter name: item]
   System.Collections.Generic.KeyedByTypeCollection`1.InsertItem(Int32 index, TItem item) +17217335
   Castle.Facilities.WcfIntegration.Internal.WcfUtils.AddBehaviors(IKernel kernel, WcfExtensionScope scope, ICollection`1 behaviors, IWcfBurden burden, Predicate`1 predicate) +299
   Castle.Facilities.WcfIntegration.WcfEndpointExtensions.Install(ServiceEndpoint endpoint, Boolean withContract, IKernel kernel, IWcfBurden burden) +201
   Castle.Facilities.WcfIntegration.ServiceHostExtensions.Castle.Facilities.WcfIntegration.IWcfExtensionVisitor.VisitEndpointExtension(IWcfEndpointExtension extension) +334
   Castle.Facilities.WcfIntegration.ServiceHostExtensions.Install(ICollection`1 extensions, IWcfBurden burden) +110
   Castle.Facilities.WcfIntegration.AbstractServiceHostBuilder.ConfigureServiceHost(ServiceHost serviceHost, IWcfServiceModel serviceModel, ComponentModel model) +931
   Castle.Facilities.WcfIntegration.AbstractServiceHostBuilder`1.Build(ComponentModel model, Uri[] baseAddresses) +50
   Castle.Facilities.WcfIntegration.WindsorServiceHostFactory`1.CreateServiceHost(String constructorString, Uri[] baseAddresses) +273
   System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1451
   System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +76
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +901

[ServiceActivationException: The service '/ProductService.svc' cannot be activated due to an exception during compilation.  The exception message is: The value could not be added to the collection, as the collection already contains an item of the same type: 'Common.Interfaces.Wcf.ArchiveSerializerContractBehaviorAttribute'. This collection only supports one instance of each type.
Parameter name: item.]
   System.Runtime.AsyncResult.End(IAsyncResult result) +654324
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210877
   System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +166

When I moved attribute back to ProductService.Interfaces. It started to work without any exceptions. The version of WCFIntegrationFacility is 3.2.0.10

Castle event wiring facility and dynamic parameters throw EventWiringException

When trying to link an event with a handler using Castle.EventWiringFacility when the target service has a dynamic dependency, I get the EventWiringException with following description: Publisher tried to start subscriber 'xxx' that is waiting for a dependency.

I have traced the code down to the facility and I have found the assertion:

private static void AssertValidHandler(IHandler handler, string subscriberKey)
{
  if (handler == null)
    throw new EventWiringException("Publisher tried to start subscriber " + subscriberKey + " that was not found");
  if (handler.CurrentState == HandlerState.WaitingDependency)
    throw new EventWiringException("Publisher tried to start subscriber " + subscriberKey + " that is waiting for a dependency");
}

The problem is that the component with dynamic dependency is always in HandlerState.WaitingDependency state.

Is there a way how to tell the Castle that it should consider the dynamic dependency as Valid instead of WaitingDependency?

If not, I think that the state should be changed or may be the assertion in EventWiringFacility.AssertValidHandler could be skipped. If I skip the assertion in debugger, everything is working fine, i.e. the service gets resolved and the event gets fired and handled.

Using a factory method instead of dynamic parameter solves the issue but is not a convenient way how to fix the problem in my application.

Please find the code below to reproduce the behavior:

using System;
using Castle.Facilities.EventWiring;
using Castle.Facilities.Startable;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace SmallTests
{
    public interface IA
    {
        string DynDep { get; }
        void EventHandler(object sender, EventArgs args);
    }

    public class A : IA
    {
        private readonly string _dynDep;

        public A(string dynDep)
        {
            _dynDep = dynDep;
        }

        public string DynDep
        {
            get { return _dynDep; }
        }

        public void EventHandler(object sender, EventArgs args)
        {
            Console.WriteLine("Event Handled");
        }
    }

    public interface IB
    {
        event EventHandler MyEvent;
        void RaiseEvent();
    }


    public class B : IB
    {
        public event EventHandler MyEvent;

        public virtual void RaiseEvent()
        {
            var handler = MyEvent;
            if (handler != null) handler(this, EventArgs.Empty);
        }
    }

    public class CastleTest
    {
        public static void CastleDynamicDependency()
        {
            var c = new WindsorContainer();
            c.AddFacility<EventWiringFacility>();
            c.AddFacility<StartableFacility>(f => f.DeferredStart());

            c.Register(Component.For<IA>().ImplementedBy<A>()
                .DynamicParameters((kernel, parameters) => parameters["dynDep"] = DateTime.Now.ToShortTimeString())
                .Named("A"));

            //This works fine, but I cannot use it in my project
            //c.Register(Component.For<IA>()
            //    .UsingFactoryMethod(kernel => new A(DateTime.Now.ToShortTimeString()))
            //    .Named("A"));

            c.Register(Component.For<IB>().ImplementedBy<B>()
                .PublishEvent(x => x.MyEvent += null,
                    y => y.To<IA>("A", s => s.EventHandler(null, null))));

            var r = c.Kernel.GetHandler("A");
            Console.WriteLine(r.CurrentState);

            var a = c.Resolve<IA>();
            Console.WriteLine(a.DynDep);

            var b = c.Resolve<IB>();
            b.RaiseEvent();

            Console.ReadLine();
        }
    }
}

I have also posted the question on stackowerflow.

Add per-object behavior configuration in WCF Facility fluent syntax

While it's super convenient that the WCF facility automatically wires up every behavior to your objects registered in the container, sometimes I only want it to apply to specific endpoints/services. Right now the only way I've found how to do this is on the ApplyXXXBehavior event, go through and inspect the object and conditionally apply the behavior if it's the type I want, otherwise do nothing.

It would be helpful if there was a way to add a specific behavior in the fluent API, like .UsingBehavior()

An alternative would be to apply an exclusion to the object in question, such as .PreventBehavior(typeof(MyServiceBehavior), typeof(MyOtherServiceBehavior))

Introduce IContributeComponentRegistrationConstruction

If I want to write some cross-cutting registration then I can use IContributeComponentModelConstruction interface that works over ComponentModel.
It's absolutely sufficient for primitive registrations but if I want to make some complex stuff then I would like to re-use nice methods (eg. DependOn) available on ComponentRegistration class.

So it would be nice to be able to alter ComponentRegistration just before ComponentModel is built.

I would be able to register my implementations of IContributeComponentRegistrationConstruction that would be probably called from DefaultKernel.Register() method.
The the interface could work over IRegistration, but just for ComponentRegistration would makes sense too for me.

Castle Windsor 3.3 XML config file component parsing error

I'm in the process of upgrading our Castle Windsor dlls from v2.1 to 3.3.
We have to use the app.config to define our components due to our installation \configuration requirements.

Since upgrading to 3.3, when I try to resolve the dependencies, I get the following error:

Castle.MicroKernel.Resolvers.DependencyResolverException :
Could not convert parameter 'myProcessor' to type 'ImyProcessor'.
----> Castle.MicroKernel.SubSystems.Conversion.ConverterException :
Could not convert expression '${myProcessor}
' to type 'Interfaces.ImyProcessor'.
Expecting a reference override like ${some key}

This appears to be caused by a change in the way the component sections of the config file are parsed in the latest version.

Our component parameters are formatted like this (i.e. split onto multiple lines)

<parameters>
    <myProcessor>
       ${myProcessor}
    </myProcessor>
</parameters>```

It only works if I change them to a single line like this:

```<parameters>
   <myProcessor>${myProcessor}</myProcessor>
</parameters>```


Is there likely to be a fix for this as reformatting all of our config files for our clients as well as updating our documentation will be considerable work.



Thanks


Chris

Deadlock

Hello! I'm using asp.net mvc 3, castle windsor 3.1.

My application recently hang on start. After attaching to a IIS Process and pressing Pause (Break-All), program break in CustomControllerFactory:

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    if (controllerType == null)
    {
        throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
    }

    // HANG HERE
    return (IController) _kernel.Resolve(controllerType);
}

For _kernel I get Cannot evaluate expression because the current thread is in a sleep, wait, or join.

Have you any ideas why this situation happens?

Use IPotentiallyMisconfiguredComponentsDiagnostic together with TypedFactoryFacility

I started to use TypedFactoryFacility, but I got immediately false positive IPotentiallyMisconfiguredComponentsDiagnostic-powered failing test. Is there any simple method how to instruct PotentiallyMisconfiguredComponentsDiagnostic to handle TypedFactoryFacility-provided components properly? I could filter handlers resulting from PotentiallyMisconfiguredComponentsDiagnostic to skip components waiting for services provided by TypedFactoryFacility, but this sounds quite demanding.

Windsor WCF integration broken after ASP.NET 4.6 upgrade

Hello,
I was trying Visual Studio 2015 CTP and got ASP.NET 4.6 upgrade during the VS installation. I use Windsor WCF integration, which seems to get broken due to this upgrade. I'm injecting Castle.Facilities.WcfIntegration.IWcfClientFactory to my services and use this simple extension method to retrieve the WCF client:

        public static T GetClient<T>(this IWcfClientFactory factory) where T : class
        {
            var componentName = typeof (T).FullName;
            return factory.GetClient<T>(componentName);
        }

The GetClient method throws this exception after the upgrade:

Castle.MicroKernel.ComponentActivator.ComponentActivatorException: WcfClientActivator: could not proxy component XXX ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at System.RuntimeMethodHandle.GetHashCode()
   at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.ServiceModel.Dispatcher.OperationSelectorBehavior.MethodInfoOperationSelector..ctor(ContractDescription description, MessageDirection directionThatRequiresClientOpSelection)
   at System.ServiceModel.Dispatcher.OperationSelectorBehavior.System.ServiceModel.Description.IContractBehavior.ApplyClientBehavior(ContractDescription description, ServiceEndpoint endpoint, ClientRuntime proxy)
   at System.ServiceModel.Description.DispatcherBuilder.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime clientRuntime)
   at System.ServiceModel.Description.DispatcherBuilder.BuildProxyBehavior(ServiceEndpoint serviceEndpoint, BindingParameterCollection& parameters)
   at System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint, Boolean useActiveAutoClose)
   at System.ServiceModel.ChannelFactory.CreateFactory()
   at System.ServiceModel.ChannelFactory.OnOpening()
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ChannelFactory.EnsureOpened()
   at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via)
   at System.ServiceModel.ChannelFactory`1.CreateChannel()
   at Castle.Facilities.WcfIntegration.WcfClientActivator.<>c__DisplayClass6.<GetChannelCreator>b__1()
   at Castle.Facilities.WcfIntegration.WcfChannelHolder.CreateChannel()
   at Castle.Facilities.WcfIntegration.WcfChannelHolder..ctor(ChannelCreator channelCreator, IWcfBurden burden, Nullable`1 closeTimeout)
   at Castle.Facilities.WcfIntegration.WcfClientActivator.Instantiate(CreationContext context)
   --- End of inner exception stack trace ---
   at Castle.Facilities.WcfIntegration.WcfClientActivator.Instantiate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)
   at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)
   at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.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.WcfIntegration.WcfClientFactorySelector.<>c__DisplayClass2.<SelectComponent>b__1(IKernelInternal k, IReleasePolicy p)
   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.IWcfClientFactoryProxy.GetClient[T](String name)

There's obviously some breaking change in ASP.NET 4.6 WCF. I already tried to debug the Windsor source code, bud wasn't able to understand the code enough to be able to figure out where the problem is. Did anyone faced the same problem? Any hints what to try to workaround the problem?

The same error ocurs after recent Windows 10 Windows Update when ASP.NET 4.6 runtime upgrade was delivered.

Deadlock on cold start of application, MVC applications, concurrent load

Hi,

In our production and performance test environments, we have ran into an issue that causes Windsor to get into a deadlocked situation. This can be reproduced with a few recycles of an IIS App pool.

Circumstances to reproduce :

  • Hundreds+ components registered to the container
  • Cold start - recycle the app
  • Throwing consistent workload as the application starts (causing it to queue in IIS / ASP.NET queues and burst onto the application when its ready)
  • Disabling ProcessModel's AutoConfig helps to reproduce the issue on a more regular basis (allows thread pool bursting)
  • We also precompiled views, but that didn't really assist

I have also worked with Microsoft Premier Support to confirm and determine that we were repeatedly seeing deadlock issues :

"We’re looking at a Deadlock.

CLR thread 0x5f holds the Writer lock on ReaderWriterLockSlim 035aa210
...and is waiting for a Reader lock on ReaderWriterLockSlim 03916f2c
CLR thread 0x68 holds the Writer lock on ReaderWriterLockSlim 03916f2c
...and is waiting for an Upgradable Reader lock on ReaderWriterLockSlim 035aa210"

Truncated call stack for the threads above (I can supply the full ones if necessary) :

OS Thread Id: 0x259c (161)
Child SP IP Call Site
2ef7d254 77c0015d [HelperMethodFrame_1OBJ: 2ef7d254] System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
2ef7d2fc 7217b80f System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)
2ef7d318 7217b7cd System.Threading.WaitHandle.WaitOne(Int32, Boolean)
2ef7d330 712f77db System.Threading.ReaderWriterLockSlim.WaitOnEvent(System.Threading.EventWaitHandle, UInt32 ByRef, Int32)
2ef7d368 714efbe2 System.Threading.ReaderWriterLockSlim.TryEnterReadLockCore(Int32)
2ef7d38c 710e8847 System.Threading.ReaderWriterLockSlim.TryEnterReadLock(Int32)
2ef7d3b8 281b1042 Castle.Core.Internal.SlimReadLockHolder..ctor(System.Threading.ReaderWriterLockSlim, Boolean)
2ef7d3c8 281b1004 Castle.Core.Internal.SlimReadWriteLock.ForReading(Boolean)
2ef7d3dc 281b0f5f Castle.Core.Internal.SlimReadWriteLock.ForReading()
2ef7d3e4 281b0ee1 Castle.Core.Internal.SimpleThreadSafeDictionary`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].Contains(System.__Canon)
2ef7d418 281b0e2a Castle.MicroKernel.Handlers.DefaultGenericHandler.Supports(System.Type)

Thread 0x4e is OS Thread 143

OS Thread Id: 0x38c0 (143)
Child SP IP Call Site
2dffd0c4 77c0015d [HelperMethodFrame_1OBJ: 2dffd0c4] System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
2dffd16c 7217b80f System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)
2dffd188 7217b7cd System.Threading.WaitHandle.WaitOne(Int32, Boolean)
2dffd1a0 712f77db System.Threading.ReaderWriterLockSlim.WaitOnEvent(System.Threading.EventWaitHandle, UInt32 ByRef, Int32)
2dffd1d8 714efbe2 System.Threading.ReaderWriterLockSlim.TryEnterReadLockCore(Int32)
2dffd1fc 710e8847 System.Threading.ReaderWriterLockSlim.TryEnterReadLock(Int32)
2dffd228 281b1042 Castle.Core.Internal.SlimReadLockHolder..ctor(System.Threading.ReaderWriterLockSlim, Boolean)
2dffd238 281b1004 Castle.Core.Internal.SlimReadWriteLock.ForReading(Boolean)
2dffd24c 281b0f5f Castle.Core.Internal.SlimReadWriteLock.ForReading()
2dffd254 281b0ee1 Castle.Core.Internal.SimpleThreadSafeDictionary`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].Contains(System.__Canon)
2dffd288 281b0e2a Castle.MicroKernel.Handlers.DefaultGenericHandler.Supports(System.Type)

The above requests originate from an MVC application, essentially starting from the controller factory which ofcourse calls upon Windsor to return a controller.

To fix the issue, I got the latest 3.2 code from Github and simply replaced the SimpleThreadSafeDictionary's ReaderWriterLockSlim to a ConcurrentDictionary. Granted, this wont work in SL etc, but I have come across others using the .net 4 code of ConcurrentDictionary in a 3.5 target with no issues.

Thoughts?

Deadlock - DefaultNamingSubsystem.GetHandlers() vs DefaultGenericHandler.type2SubHandler

We have found a deadlock with 2 threads trying to resolve 2 components (c1 and c2) implementing 2 separate generic interfaces, but then component c1 has a dependency which is in turn dependent on component c2.

In terms of code it happens because of following:
Imagine thread t1 accessing DefaultNamingSubsystem.GetHandlers() via DefaultGenericHandler.GetSubHandler (this locks type2SubHandler in that class). Another thread t2, accesses the same DefaultNamingSubsystem.GetHandlers() from Resolve(), acquires upgradable lock, and then in GetHandlersNoLock routine calls Supports(service) on the same DefaultGenericHandler (this will require access to type2SubHandler which is already held by thread t1). Thread t1 in the mean time awaits upgradable read lock from thread t2. Deadlock

This issue was found in 3.2 and confirmed in latest 3.2.1 (which means fix to IOC-370 didn't resolve this specific case).

XML Config Array Parameters not populating when registering multiple dependencies

I think I've found a bug with XML Inline parameters. I'm using this feature as strongly typed configuration as described in the docs here: http://docs.castleproject.org/Windsor.XML-Inline-Parameters.ashx

In particular I'm having trouble loading an array/list. It works fine in isolation, but as soon as I register other dependencies it the array stops being populated. However the basic parameters do. It seems to specifically be when I register multiple dependencies e.g.
container.Register(Classes.FromThisAssembly().Pick().WithServiceFirstInterface());

Full example with failing test is here:
https://gist.github.com/ztsmith/9426076

WcfIntegration: System.TypeLoadException occurred in mscorlib.dll

I use Windsor together with WCF and I'm getting this exception in Visual Studio 2013 (2012 is fine):

System.TypeLoadException occurred
  _HResult=-2146233054
  _message=GenericArguments[0], 'System.ServiceModel.ServiceHostBase', on 
           'Castle.Facilities.WcfIntegration.IChannelFactoryBuilder`1[M]' 
           violates the constraint of type parameter 'M'.
  HResult=-2146233054
  IsTransient=false
  Message=GenericArguments[0], 'System.ServiceModel.ServiceHostBase', on 
          'Castle.Facilities.WcfIntegration.IChannelFactoryBuilder`1[M]' 
          violates the constraint of type parameter 'M'.
  ResourceId=0
  TypeName=""
  InnerException: 

I use WCFFacility and I start WCF host by

host = new DefaultServiceHostFactory().CreateServiceHost(typeof(IAdminServices).AssemblyQualifiedName, new Uri[0]);
host.Open();

In Windows Forms application (self hosted service). In IIS svc service I use

<%@ ServiceHost
  Language="C#" Service="MyService"
  Factory="Castle.Facilities.WcfIntegration.DefaultServiceHostFactory, Castle.Facilities.WcfIntegration"
  %>

Problem appears in both cases. I use version 3.3.0 of the library.

Linux path for autoregistration

Hi,
On:
Castle.Windsor/MicroKernel/Registration/AssemblyFilter.cs
line 208
ToUpper method prevents working with Mono/Linux
Thank you

Race condition in PoolableLifestyleManager.CreatePool

This was already detected in http://issues.castleproject.org/youtrack/issue/IOC-381.

Further analysis shows, that parallel Execution on CreatePool will fail with a ComponentRegistrationException. A poosible Bugfix would be to introduce a static lock Object:

private static object poolFactoryLock = new object();
protected IPool CreatePool(int initialSize, int maxSize)
{
    if (!Kernel.HasComponent(typeof(IPoolFactory)))
    {
        lock (poolFactoryLock)
        { 
            if (!Kernel.HasComponent(typeof(IPoolFactory))) // Avoid the race
            {
                Kernel.Register(Component.For<IPoolFactory>().ImplementedBy<DefaultPoolFactory>().NamedAutomatically("castle.internal-pool-factory"));
            }
        }
    }
}

I did some unittest to Repro it (PooledLifestyleManagerTestCase):

        [Test]
        public void CreatePoolRaceCondition()
        {
            using (AutoResetEvent evt = new AutoResetEvent(false))
            {
                MyKernel kernel = new MyKernel(evt);

                var manager1 = new MyClass();
                var manager2 = new MyClass();

                manager1.Init(null, kernel, null);
                manager2.Init(null, kernel, null);

                Task.Factory.StartNew(() => manager1.CreatePool());
                Task.Factory.StartNew(() => manager2.CreatePool());

                Thread.Sleep(TimeSpan.FromSeconds(5));
                evt.Set();
                Thread.Sleep(TimeSpan.FromSeconds(5));

                Assert.That(kernel.parallelCount, Is.EqualTo(0));
            }
        }

        private class MyClass : PoolableLifestyleManager
        {
            public MyClass()
                : base(1, 2)
            {            
            }

            public void CreatePool()
            {
                base.CreatePool(2, 5).Dispose();
            }
        }

        private class MyKernel : IKernel
        {
            private readonly AutoResetEvent evt;
            public event ComponentDataDelegate ComponentRegistered;
            public event ComponentModelDelegate ComponentModelCreated;
            public event EventHandler AddedAsChildKernel;
            public event EventHandler RemovedAsChildKernel;
            public event ComponentInstanceDelegate ComponentCreated;
            public event ComponentInstanceDelegate ComponentDestroyed;
            public event HandlerDelegate HandlerRegistered;
            public event HandlersChangedDelegate HandlersChanged;
            public event DependencyDelegate DependencyResolving;
            public event EventHandler RegistrationCompleted;
            public event ServiceDelegate EmptyCollectionResolving;

            public MyKernel(AutoResetEvent evt)
            {
                this.evt = evt;
            }

            public void Dispose()
            {
            }

            object IKernel.this[string key]
            {
                get { throw new NotImplementedException(); }
            }

            object IKernel.this[Type service]
            {
                get { throw new NotImplementedException(); }
            }

            public void AddComponent(string key, Type classType)
            {
                throw new NotImplementedException();
            }

            public void AddComponent(string key, Type classType, LifestyleType lifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent(string key, Type classType, LifestyleType lifestyle, bool overwriteLifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent(string key, Type serviceType, Type classType)
            {
                throw new NotImplementedException();
            }

            public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle, bool overwriteLifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>()
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>(LifestyleType lifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>(LifestyleType lifestyle, bool overwriteLifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>(Type serviceType)
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>(Type serviceType, LifestyleType lifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponent<T>(Type serviceType, LifestyleType lifestyle, bool overwriteLifestyle)
            {
                throw new NotImplementedException();
            }

            public void AddComponentInstance<T>(object instance)
            {
                throw new NotImplementedException();
            }

            public void AddComponentInstance<T>(Type serviceType, object instance)
            {
                throw new NotImplementedException();
            }

            public void AddComponentInstance(string key, object instance)
            {
                throw new NotImplementedException();
            }

            public void AddComponentInstance(string key, Type serviceType, object instance)
            {
                throw new NotImplementedException();
            }

            public void AddComponentInstance(string key, Type serviceType, Type classType, object instance)
            {
                throw new NotImplementedException();
            }

            public void AddComponentWithExtendedProperties(string key, Type classType, IDictionary extendedProperties)
            {
                throw new NotImplementedException();
            }

            public void AddComponentWithExtendedProperties(string key, Type serviceType, Type classType, IDictionary extendedProperties)
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility(string key, IFacility facility)
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility<T>(string key) where T : IFacility, new()
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility<T>(string key, Action<T> onCreate) where T : IFacility, new()
            {
                throw new NotImplementedException();
            }

            public object Resolve(string key, object argumentsAsAnonymousType)
            {
                throw new NotImplementedException();
            }

            public object Resolve(string key, IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public IComponentModelBuilder ComponentModelBuilder { get; private set; }
            public IConfigurationStore ConfigurationStore { get; set; }
            public GraphNode[] GraphNodes { get; private set; }
            public IHandlerFactory HandlerFactory { get; private set; }
            public IKernel Parent { get; set; }
            public IProxyFactory ProxyFactory { get; set; }
            public IReleasePolicy ReleasePolicy { get; set; }
            public IDependencyResolver Resolver { get; private set; }

            public void AddChildKernel(IKernel kernel)
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility(IFacility facility)
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility<T>() where T : IFacility, new()
            {
                throw new NotImplementedException();
            }

            public IKernel AddFacility<T>(Action<T> onCreate) where T : IFacility, new()
            {
                throw new NotImplementedException();
            }

            public void AddHandlerSelector(IHandlerSelector selector)
            {
                throw new NotImplementedException();
            }

            public void AddHandlersFilter(IHandlersFilter filter)
            {
                throw new NotImplementedException();
            }

            public void AddSubSystem(string name, ISubSystem subsystem)
            {
                throw new NotImplementedException();
            }

            public IHandler[] GetAssignableHandlers(Type service)
            {
                throw new NotImplementedException();
            }

            public IFacility[] GetFacilities()
            {
                throw new NotImplementedException();
            }

            public IHandler GetHandler(string name)
            {
                throw new NotImplementedException();
            }

            public IHandler GetHandler(Type service)
            {
                throw new NotImplementedException();
            }

            public IHandler[] GetHandlers(Type service)
            {
                throw new NotImplementedException();
            }

            public ISubSystem GetSubSystem(string name)
            {
                throw new NotImplementedException();
            }

            public bool HasComponent(string name)
            {
                throw new NotImplementedException();
            }

            public int parallelCount = 0;
            private bool registered;

            public bool HasComponent(Type service)
            {
                return registered;
            }

            public IKernel Register(params IRegistration[] registrations)
            {
                Interlocked.Increment(ref parallelCount);
                evt.WaitOne();
                registered = true;
                Interlocked.CompareExchange(ref parallelCount, 0, 1);
                return null;
            }

            public void ReleaseComponent(object instance)
            {
                throw new NotImplementedException();
            }

            public void RemoveChildKernel(IKernel kernel)
            {
                throw new NotImplementedException();
            }

            public object Resolve(Type service)
            {
                throw new NotImplementedException();
            }

            public object Resolve(Type service, IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public object Resolve(Type service, object argumentsAsAnonymousType)
            {
                throw new NotImplementedException();
            }

            public object Resolve(string key, Type service)
            {
                throw new NotImplementedException();
            }

            public T Resolve<T>(IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public T Resolve<T>(object argumentsAsAnonymousType)
            {
                throw new NotImplementedException();
            }

            public T Resolve<T>()
            {
                return (T)(object)new DummyFactory();
            }

            public T Resolve<T>(string key)
            {
                throw new NotImplementedException();
            }

            public T Resolve<T>(string key, IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public object Resolve(string key, Type service, IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public Array ResolveAll(Type service)
            {
                throw new NotImplementedException();
            }

            public Array ResolveAll(Type service, IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public Array ResolveAll(Type service, object argumentsAsAnonymousType)
            {
                throw new NotImplementedException();
            }

            public TService[] ResolveAll<TService>()
            {
                throw new NotImplementedException();
            }

            public TService[] ResolveAll<TService>(IDictionary arguments)
            {
                throw new NotImplementedException();
            }

            public TService[] ResolveAll<TService>(object argumentsAsAnonymousType)
            {
                throw new NotImplementedException();
            }
        }

        private class DummyFactory : IPoolFactory
        {
            public IPool Create(int initialsize, int maxSize, IComponentActivator activator)
            {
                return new MyPool();
            }
        }

        private sealed class MyPool : IPool
        {
            public void Dispose()
            {
            }

            public bool Release(object instance)
            {
                throw new NotImplementedException();
            }

            public object Request(CreationContext context, Func<CreationContext, Burden> creationCallback)
            {
                throw new NotImplementedException();
            }
        }

Is null a valid value for a dependency (from a factory method)?

Per the docs

No, it's not. null means no value and is ignored by Windsor. Be explicit - if the value is optional provide overloaded constructor that does not include it. Alternatively specify explicitly null as the default value in the signature of the constructor. This is the only scenario where Windsor will allow passing null.

In my case I've used the alternate approach and specified null as the default value in the constructor. And yet, my factory method throws an exception

{"Factory method creating instances of component 'Late bound ConsoleApplication1.IFoo' returned null. This is not allowed and most likely a bug in the factory method."}

Here's a gist to demonstrate

WcfClientActivator opens the channel on activation

Hi,
In Wcf facility, WcfClientActivator opens the channel on component activation. I know this is intended since it is well documented:

"Always Open the channel before being used to prevent serialization of requests.
http://blogs.msdn.com/wenlong/archive/2007/10/26/best-practice-always-open-wcf-client-proxy-explicitly-when-it-is-shared."

The problem I am experiencing with this behavior is that if a component is dependent on a wcf client, and the service isn't available (ServiceEndpointNotFoundException is thrown for instance) on the component activation - the application crashes.

I'd like to have a behavior similar to the refresh policy - use the client within a try-catch scope, and if an exception occurs you can still keep using it - castle recycles it for you.

This can be done if one could specify whether to open the client on activation (default value will be true) or not.

Generic Parameter Constraint Violations

I'm seeing an enormous number of TypeLoadExceptions in my application, which although they are handled, the quantity of them is significantly impacting application startup time out of the debugger.

This occurs in DefaultGenericHandler.SupportsAssignable() because generic types are attempting to be created using type parameters that do not satisfy the constraints on the interface. I didn't see anything upstream from that point that would validate these constraints; is there?

Example:

   interface IDoSomething<out T> where T : IApple
   interface IDoSomethingUnrelated<T> where T : ConcreteSpaceshipClass

   class RedDelicious : IApple

SupportsAssignable() gets service of type IDoSomething<RedDelicious> and modelService of type IDoSomethingUnrelated<>. It then is trying to create the generic IDoSomethingUnrelated<RedDelicious>.

Should it even get to this point? If so, are there other concerns that prevent adding checks against the type parameter constraints before attempting to make the generic type?

WcfFacility hosted in windows service, cannot publish mex with installer

I am hosting wcf service library inside windows service, I failed to enable mex publishing via installer, I have to manually add service behaviour and MetadataExchangeBindings after calling new DefaultServiceHostFactory().CreateServiceHost

var binding = MetadataExchangeBindings.CreateMexHttpBinding();
var mexAddress = "http://localhost:8744/TVIRecorderWcfService/mex";
var behaviour = new ServiceMetadataBehavior() {HttpGetEnabled = true};


serviceHost.Description.Behaviors.Add(behaviour);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, mexAddress);

this is original app.config created by visual studio(I do not use app.config for wcf setting in my windows service )

    <system.serviceModel>
    <services>
      <service name="TVIRecorder.WcfService.TVIRecorderWcfService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/TVIRecorder.WcfService/TVIRecorderWcfService/" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="TVIRecorder.WcfService.ITVIRecorderWcfService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
           <serviceMetadata httpGetEnabled="True" />
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

this is my installer

public class WindsorInstaller: IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddFacility<LoggingFacility>(f => f.UseLog4Net());

        container
            .AddFacility<WcfFacility>(f =>
            {
                f.CloseTimeout = TimeSpan.Zero;
            });


        string baseAddress = "http://localhost:8744/TVIRecorderWcfService/";

        container.Register(

            Component
                .For<ITVIRecorderWcfService>()
                .ImplementedBy<TVIRecorderWcfService>()
                .AsWcfService(
                new DefaultServiceModel()
                    .AddBaseAddresses(baseAddress)
                    .Hosted()
                    //publish doesn't either put here or below
                    //.PublishMetadata(x => x.EnableHttpGet()).Discoverable()
                    .AddEndpoints(WcfEndpoint
                        .BoundTo(new BasicHttpBinding()))
                        //.PublishMetadata(x=>x.EnableHttpGet()).Discoverable()
                        ).LifestyleSingleton()
                        ,

            Component
                .For<ServiceBase>()
                .ImplementedBy<TVIRecorderService>());
    }
}

Pooled items not being disposed properly

If I have an object that implements IDisposable that is registered as lifestyle pooled, when I release the object it returns to the pool properly. However, if I attempt to dispose the container itself the Dispose() method is never called. I wrote a simple unit test to demonstrate. Also, this behavior appears to manifest only for pooled lifestyle. Is this by design? It only appears to do this for pooled objects. If I run the same test with Transient or Singletons it will pass.

    [Fact]
    public void ReleasingPoolDisposesItems()
    {
        // Arrange.
        bool result = false;
        var container = new WindsorContainer();
        container.Register(Component.For<DisposableMock>().LifestylePooled(1, 5));
        container.Release(container.Resolve<DisposableMock>(new { disposeAction = new Action(() => result = true) }));

        // Act.
        container.Dispose();

        // Assert.
        Assert.True(result);
    }

public class DisposableMock : IDisposable
{
    private Action disposeAction;

    public DisposableMock(Action disposeAction)
    {
        this.disposeAction = disposeAction;
    }

    public void Dispose()
    {
        disposeAction();
    }
}

Channels are always Disposed even if they are in Faulted state [FACILITIES-167]

Relogging YouTrack issue logged by Antineutrino 4 months ago.
http://issues.castleproject.org/youtrack/issue/FACILITIES-167


Channels are always Disposed even if they are in Faulted state. Calling Dispose always triggers a CommunicationObjectAbortedException. This results in crashes of the IIS server process.

They should be aborted first.

Server stack trace: 
   bei System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
Exception rethrown at [0]: 
   bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   bei System.IDisposable.Dispose()
   bei Castle.MicroKernel.LifecycleConcerns.DisposalConcern.Apply(ComponentModel model, Object component)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.ApplyConcerns(IEnumerable`1 steps, Object instance)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.ApplyDecommissionConcerns(Object instance)
   bei Castle.Facilities.WcfIntegration.WcfClientActivator.ApplyDecommissionConcerns(Object instance)
   bei Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalDestroy(Object instance)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Destroy(Object instance)
   bei Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Release(Object instance)
   bei Castle.MicroKernel.Handlers.DefaultHandler.ReleaseCore(Burden burden)
   bei Castle.MicroKernel.Handlers.AbstractHandler.Release(Burden burden)
   bei Castle.MicroKernel.Burden.Release()
   bei XXXXXXXXXXX.DependencyInjection.Castle.DependencyInjectionContainer.FixedLifecycledComponentsReleasePolicy.Release(Object instance)
   bei Castle.MicroKernel.DefaultKernel.ReleaseComponent(Object instance)
   bei Castle.MicroKernel.Internal.LazyEx`1.Dispose()
   bei Castle.MicroKernel.LifecycleConcerns.DisposalConcern.Apply(ComponentModel model, Object component)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.ApplyConcerns(IEnumerable`1 steps, Object instance)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.ApplyDecommissionConcerns(Object instance)
   bei Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalDestroy(Object instance)
   bei Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Destroy(Object instance)
   bei Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Release(Object instance)
   bei Castle.MicroKernel.Handlers.DefaultHandler.ReleaseCore(Burden burden)
   bei Castle.MicroKernel.Handlers.AbstractHandler.Release(Burden burden)
   bei Castle.MicroKernel.Burden.Release()
   bei Castle.MicroKernel.Burden.<Release>b__0(Burden c)
   bei System.Collections.Generic.List`1.ForEach(Action`1 action)
   bei Castle.MicroKernel.Burden.Release()
   bei Castle.MicroKernel.Lifestyle.Scoped.ScopeCache.<Dispose>b__0(Burden b)
   bei Castle.Core.Internal.CollectionExtensions.ForEach[T](IEnumerable`1 items, Action`1 action)
   bei Castle.MicroKernel.Lifestyle.Scoped.ScopeCache.Dispose()
   bei Castle.MicroKernel.Lifestyle.Scoped.DefaultLifetimeScope.Dispose()
   bei Castle.Facilities.WcfIntegration.Lifestyles.WcfOperationScopeHolder.Dispose()
   bei Castle.Facilities.WcfIntegration.Lifestyles.WcfOperationScopeHolder.Shutdown(Object sender, EventArgs e)
   bei System.ServiceModel.OperationContext.FireOperationCompleted()

A temporary workaround is to modify the Apply method in the DisposalConcern in Windsor:

public void Apply(ComponentModel model, object component)
{
    // HACK
    var attributes = component.GetType().GetCustomAttributes(typeof(ServiceContractAttribute), true);
    if (attributes.Any())
    {
        var channel = component as IChannel;
        if (channel != null && channel.State == CommunicationState.Faulted)
        {
            channel.Abort();
        }
    }

    var disposable = component as IDisposable;
    if (disposable == null)
    {
        return;
    }
    disposable.Dispose();
}

Lazy<T> marks the component as potentially misconfigured

When i add the following :

 container.Register(Component.For<ILazyComponentLoader>()
        .ImplementedBy<LazyOfTComponentLoader>());

And then later on try to use a component in a lazy context, marks the dependency as IsAwaitingDependency on the potentially misconfigured diagnostic, allthough it resolves correctly.

Never resolved transient startable component will not stop

Here is a test class that describes my problem.

https://gist.github.com/maciejw/01ff8ac9bec79ec49973

Is this a bug or a feature?

test results:

Test Name: When_container_is_disposed_startable_component_never_resolved_explicitly_should_stop(Transient)
Test Outcome: Failed
Test Duration: 0:00:05,029
Result StandardOutput: Created
Started

Test Name: When_container_is_disposed_startable_component_never_resolved_explicitly_should_stop(Singleton)
Test Outcome: Passed
Test Duration: 0:00:00,007
Result StandardOutput: Created
Started
Stopped
Disposed

Attempting to resolve a non-generic type with a backing generic implementation causes an exception to be thrown

If I have a non-generic interface that's implemented using a parameterized type, when I attempt to resolve it an exception will be thrown stating that the container doesn't have enough information to determine what to construct (expected). However, if I add a IGenericImplementationMatchingStrategy that provides the parameter type, then an Invalid Operation exception will be thrown when calling Type.GetGenericTypeDefinition() from within DefaultGenericHandler.AdaptServices().

Duplex contract Fromconfiguration not working

I was trying to create a Duplex client model using the "FromConfiguration" feature provided by castle wcf facility. It works fine when registering the service on client side when at runtime when I try to resolve it, it throws error.

DuplexClientModel model = new DuplexClientModel
    {
        Endpoint = WcfEndpoint.ForContract<IServiceWithCallback>()
            .FromConfiguration("IServiceWithCallback_Endpoint")

    }.Callback(callbackService);

Error is: WcfClientActivator: Could not find proxy component 7c9e34c6-72c4-44b8-a082-e4e4ad3d7777"

Innerexception: The Address property on ChannelFactory.Endpoint was null. The ChannelFactory's Endpoint must have a valid Address specified.

Client App.Config-

endpoint address="net.tcp://localhost:9898/ServiceWithCallback" binding="netTcpBinding" bindingConfiguration="netTcpBindingConfiguration" contract="Castle.Facilities.WcfIntegration.Tests.Components.IServiceWithCallback" name="IServiceWithCallback_Endpoint" />

Using the same service but using the "BoundTo" and "At" instead of "FromConfiguration" it works just fine.

DuplexClientModel model = new DuplexClientModel
    {
        Endpoint = WcfEndpoint.ForContract<IServiceWithCallback>()                 
           .BoundTo(new NetTcpBinding())
           .At("net.tcp://localhost:9898/ServiceWithCallback")

    }.Callback(callbackService);

Deadlock between DefaultPool and LifecycledComponentsReleasePolicy

Thread 1:

TypedFactoryComponentResolver.Resolve() causes (through some intermediaries) a call to DefaultPool.Request which locks DefaultPool.rwlock for writing then eventually proceeds to LifecycledComponentsReleasePolicy.Track() which tries to obtain its lock for writing.

Thread 2:

TypedFactoryComponentResolver.Release() goes through LifecycledComponentsReleasePolicy.Release() first which obtains its lock for writing and then proceeds to Burden.Release() while still holding the lock which eventually makes its way to DefaultPool.Release() which tries to obtain DefaultPool.rwlock for writing.

Since the order of obtaining locks is exactly opposite, a deadlock happens under heavy load.

Method Injection

In the scenario where we have a service whos construction needs to be relegated to an external component (think web service or third party library) and there is a specific method that can be called and the parameters, if any, of that method are components or services that are resolvable in the container. How could we go about registering this without the use of a factory?

I guess what i am asking is if there is any way to do method injection in castle windsor and use the result(s) as instances for the registered services?

An example of this would be a web service that is being used for authoriztion returns a custom user object or even simply a service that returns some configuration

my thought for the code would be container.register(Component.For().UsingMethod("MethodName")

Resolve component implementing single generic interface throws ArgumentException

I'd like to resolve component which implements generic interface with different generic parameters. My code:

    public interface IOuterService<T, U> : ICanBeResolvedByContainer
    {
    }

    public interface IWrap1<T> : ICanBeResolvedByContainer
    {
    }

    public interface IWrap2<T> : ICanBeResolvedByContainer
    {
    }

    public interface IService1<T, U> : IOuterService<IWrap1<T>, U>
    {
    }

    public interface IService2<T, U> : IOuterService<IWrap2<T>, U>
    {
    }

    public class Component<T, U> : IService1<T, U>, IService2<T, U>
    {
    }

Then let's register everything which implements ICanBeResolvedByContainer:

    var container = new WindsorContainer();
    container.Register(
        Classes
            .FromAssemblyContaining<ICanBeResolvedByContainer>()
            .BasedOn<ICanBeResolvedByContainer>()
            .WithServiceFromInterface(typeof (ICanBeResolvedByContainer))
            .WithServiceSelf());
    var dep = container.Resolve<Component<int, int>>();

The last line throws ArgumentException: An item with the same key has already been added.

Expected behavior: resolve or throw meaningful exception.

My investigations lead to problem in DefaultGenericHandler.EnsureInterfaceMappingInitialized. GetGenericTypeDefinition is used here as dictionary key, and there are obviously two similar keys in this case: typeof(IOuterService<,>).

Is this just a not implemented case?

Property injection resolve issue with DynamicParameters

Whenever using a DynamicParameters in register hierarchy, the state of some services (that depends to those that used DynamicParameters) changed to "Some dependencies of this component could not be statically resolved.
'SampleNamespace.DbContext' is waiting for the following dependencies:
Parameter 'connectionString' which was not provided. Did you forget to set the dependency?"
at that time constructor injection works perfect!
How can we solve this issue?
[sorry for bad English]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.