Reputation: 126
I am trying to modify an existing WebForms application and would like to use Autofac. As far as I can tell, I've set up the application according to the documentation (http://autofac.readthedocs.org/en/latest/integration/webforms.html#structuring-pages-and-user-controls-for-di).
Web page code with a public property
public partial class MyTestPage : Page
{
public ILogger Logger { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//page load code here
web.config
<modules>
<add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" preCondition="managedHandler" />
<add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" preCondition="managedHandler" />
</modules>
Global.asax.cs
public class Global : HttpApplication, IContainerProviderAccessor
{
static IContainerProvider _containerProvider;
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterType<Logger>().As<ILogger>().InstancePerRequest();
_containerProvider = new ContainerProvider(builder.Build());
}
When I try to load the page, Autofac throws this exception.
No constructors on type 'NLog.Logger' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.
What am I missing here? Why is Autofac looking for a constructor instead of picking up the public property?
Upvotes: 0
Views: 349
Reputation: 3329
The problem here is that Autofac is trying to create an instance of Logger
class to inject it to your MyTestPage
. It tries using default, parameter-less constructor, which is unavailable. So the problem is not with your page, but with your logger registration.
I am not familiar to NLog
, but according to tutorial, you are suppose to use LogManager
to create instances of Logger
, e.g.
Logger logger = LogManager.GetCurrentClassLogger();
or
Logger logger = LogManager.GetLogger("MyClassName");
So you should change your registration to something like this (not tested):
builder.Register(c => LogManager.GetCurrentClassLogger()).As<ILogger>().InstancePerRequest();
As I mentioned above, I am not familiar with NLog, but I assume NLog Logger
class implements ILogger
interface.
EDIT:
This module should handle what you are trying to achieve.
Upvotes: 1