I have a Asp.Net API (.NET Framework 4.7.2). We recently updated Autofac to version 6.2.0. Autofac does not like some of our classes that don't have a public constructor.
Example class:
public sealed class User
{
private static readonly Lazy<User> Lazy = new Lazy<User>(() => new User());
public static User Instance => Lazy.Value;
private User()
{
}
public DateTime UserDate { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Theme { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsLoggedIn { get; set; }
public PrismApplication LoggedInTo {get;set;}
}
I put in a work around to exclude these classes for the Autofac ContainerBuilder in Global.asax.cs
:
...
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var targetAssembly = typeof(SalesDocumentCommandHandler).GetTypeInfo().Assembly;
var _skippedTypes = new HashSet<Type>();
_skippedTypes.Add(typeof(User));
_skippedTypes.Add(typeof(ReportClass));
_skippedTypes.Add(typeof(PrismApplication));
_skippedTypes.Add(typeof(OutboundEmailType));
_skippedTypes.Add(typeof(OEDataset.OERow));
_skippedTypes.Add(typeof(OEDataset.OESOPUserDefinedRow));
_skippedTypes.Add(typeof(OEDataset.OESOPPOLinkRow));
_skippedTypes.Add(typeof(OEDataset.OELineCommentRow));
_skippedTypes.Add(typeof(OEDataset.OEHeaderCommentRow));
_skippedTypes.Add(typeof(OEDataset.SOPTaxBreakupRow));
_skippedTypes.Add(typeof(OEDataset.OEHDetailRow));
_skippedTypes.Add(typeof(OEDataset.OEHHeaderRow));
_skippedTypes.Add(typeof(OEDataset.OEDetailRow));
_skippedTypes.Add(typeof(OEDataset.OEHeaderRow));
builder.RegisterAssemblyTypes(targetAssembly).Where(x => !_skippedTypes.Contains(x))
.As(type => type.GetInterfaces()
.Where(interfacetype => interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))
|| interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))
.AsSelf()
.InstancePerDependency();
targetAssembly = typeof(SalesDocumentCreatedEvent).GetTypeInfo().Assembly;
builder.RegisterAssemblyTypes(targetAssembly).Where(x => !_skippedTypes.Contains(x))
.As(type => type.GetInterfaces()
.Where(interfacetype => interfacetype.IsAssignableFrom(typeof(ICommandHandler<>))
|| interfacetype.IsAssignableFrom(typeof(IEventHandler<>))))
.AsSelf()
.InstancePerDependency().PublicOnly();
...
Isn't there a better way?