drewb
drewb

Reputation: 101

#botframework dependency injection

I am attempting to use Autofac to provide a service to a dialog class in my chat bot via dependency injection. I have configured the Autofac container as below in my Global.asax.cs file:

var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;

builder
    .RegisterType<RootDialog>()
    .As<IDialog<object>>()
    .InstancePerDependency();

builder
    .RegisterType<GoogleAnalyticsService>()
    .Keyed<IAnalyticsService>(FiberModule.Key_DoNotSerialize)
    .AsImplementedInterfaces()
    .SingleInstance();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterWebApiFilterProvider(config);

builder.Update(Conversation.Container);

This code in my MessageController class successfully resolves the dialog:

using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
{
    await Conversation.SendAsync(activity, () => scope.Resolve<IDialog<object>>());
}

When the dialog is first resolved and the constructor is run, the implementation of IAnalyticsService is injected successfully as observed while debugging in Visual Studio.

[Serializable]
public class RootDialog : IDialog<object>
{
    private readonly IAnalyticsService _analyticsService;

    public RootDialog(IAnalyticsService analyticsService)
    {
        SetField.NotNull(out _analyticsService, nameof(analyticsService), analyticsService);
    }

}

However when attempting to access the _analyticsService variable after this stage (i.e. when processing a message sent by the user) it is always null. I have tried setting a NonSerializable attribute on it, but this did not make any difference. Further debugging also showed that the constructor is not hit again.

Can anybody advise on why this variable would be null, and any potential solutions to the issue?

Upvotes: 2

Views: 408

Answers (1)

drewb
drewb

Reputation: 101

After cleaning and rebuilding again my solution worked. Frustrating.

Upvotes: 1

Related Questions