0

In my WCF project I register my interface using Castle Windsor in the global.asax:

            Component.For<IStrategy>()
                .ImplementedBy<MyStrategy>()
                .LifestylePerWcfOperation(),

Then later on in the same file I configure NHibernate using FluentNhibernate using a provider:

FluentConfiguration configuration = Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2008.ConnectionString(myConnString)
                .Provider<ConnectionProvider>())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TenantMap>()) etc etc

However this ConnectionProvider is hosted in a common shared dll library as there are other WCF services that need to use it. I want to register this dependency as below but it doesn't work which means I have to manually new up a instance.

    public ConnectionProvider()
    {    
        // doesnt work
        using (IDependencyScope scope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope())
        {
            _myStrategy = scope.GetService<IStrategy>();
        }
    }

Is there anyway to make this work? Its like its lost scope as its in another assembly now. In the same assembly the DependencyScope works fine and creates an instance, but I want to keep it in a shared dll.

EDIT: The error I get is "System.Web.Http.Dependencies.EmptyResolver" on a watch on this bit of code: GlobalConfiguration.Configuration.DependencyResolver

User101
  • 748
  • 2
  • 10
  • 29

1 Answers1

0

I can see several problems with the code above:

1) You are registering IStrategy,MyStrategy with a per WcfOperation lifestyle. This means that windsor will create a strategy for each WcfOperation. On the otherhand you are trying to manually set the lifestyle of the component by using scope.GetService. For scope.GetService to work you will need a lifestyle scoped.

2) Assuming that the code for ConnectionProvider above is the constructor, it seems that the constructor is trying to get something from the container. This is in general a bad idea, and even worse when using an Ioc container like windsor. Instead pass the IStrategy to the constructor (inject it).

3) Seeing that you are calling the container a constructor here, probably means that you are not adhering to the principle that there should be only 3 calls to the container, 1 to register component, 1 to retrieve a top level component, and 1 to release the container.

I suggest you read a bit more about depedency injection and Ioc containers in general to fully understand how to work with this container.

Marwijn
  • 1,681
  • 15
  • 24