我是基于Autofac的依赖项注入的新手。根据我们公司的要求,我必须在要创建的新Web API中使用它。以下是我的代码。我在Autofac中使用IocConfig类在Web API中创建和注入对象。
public class MemberCodeController : ApiController
{
private IMemberStrategy memberStrategy;
private IMemberDetail memberDetail;
//Constructor dependency injection through Autofac
public MemberCodeController(IMemberStrategy memberStrategy,
IMemberDetail memberDetail)
{
this.memberStrategy = memberStrategy;
}
public IHttpActionResult CreateMember(string email)
{
memberDetail.DataFields.RegisterCode = GetCode();
memberDetail.Email = email;
}
}
The MemberDetail class:
public interface IMemberDetail
{
String Email { get; set; }
DataFields DataFields { get; set; }
}
public class MemberDetail : IMemberDetail
{
public String Email { get; set; }
public DataFields DataFields { get; set; }
}
public interface IDataFields
{
String RegisterCode { get; set; }
}
public class DataFields : IDataFields
{
public String RegisterCode { get; set; }
}
IocConfig:
public class IocConfig
{
//Autofac configuration
public static void Configure()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MemberStrategy>().As<IMemberStrategy>();
builder.RegisterType<DataFields>().As<IDataFields>();
builder.RegisterType<MemberDetail>().As<IMemberDetail>();
IContainer container = builder.Build();
AutofacWebApiDependencyResolver resolver = new
AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
我遇到的问题是,当我尝试使用此行时, memberDetail.DataFields.RegisterCode = GetCode(); DataFields为空。显然,Autofac在构造MemberDetail对象时并未创建它。
答案 0 :(得分:0)
MemberDetail在其构造函数中未显示对IDataField的依赖。
因此Autofac不会为此依赖关系创建实例。
添加这样的依赖项将注入一个实例:
public class MemberDetail : IMemberDetail
{
public String Email { get; set; }
public IDataFields DataFields { get; set; }
public MemberDetail(IDataFields dataFields)
{
DataFields = dataFields;
}
}
我也将DataFields成员类型更改为IDataFields,以建立对接口的依赖。
答案 1 :(得分:0)
MemberDetail对象已正确创建。您缺少的是DataFields属性的初始化。将构造函数添加到DataFields类并在那里初始化DataFields属性,您的问题将消失。