How can I fix my Castle Windsor registration? - autofac

I've tried so hard to make this work, but when I try to resolve IConfigReader from the container it says that I haven't registered any components. I've read through it over and over again. Baffled!
var builder = new ContainerBuilder();
builder.RegisterType<ConsoleLogger>().As<ILogger>();
var output = new StringWriter();
builder.RegisterInstance(output).As<TextWriter>();
builder.Register(c => new ConfigReader("mysection")).As<IConfigReader>();
var container = builder.Build();
using(var scope = container.BeginLifetimeScope())
{
var reader = container.Resolve<IConfigReader>();
}

Related

Autofac Performance Tuning

We have implmeneted the following Autofac code using SingleInstance in c# code. We found its taking time around 3 to 4 seconds for intiating the constructors for all the services for every time when we call the particular services.
Please find below the following code implementation.
private static void RegisterDependency(HttpConfiguration config)
{
Log.Trace("Registering dependencies");
var builder = new ContainerBuilder();
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
var configService = new ConfigurationService(httpContextBase, new CacheWrapper());
var stubModeValue = configService.GetResourcePreferenceValueByKeyName("stubMode", "N");
var isStubMode = "Y".Equals(stubModeValue, StringComparison.OrdinalIgnoreCase);
builder.RegisterAssemblyTypes(typeof(ClientService).Assembly).Where(x => x.isClass && x.isPublic && !x.isAbstract)
.Where(x => isStubMode = x.Name.EndsWith("stub").AsImplementedInterface();
RegisterServiceProxy<ExternalService1>(builder);
RegisterServiceProxy<ExternalService2>(builder);
RegisterServiceProxy<ExternalService3>(builder);
builder.Register<IUserProfile>(x => OwnerIdentityAndRoleProfile.Current).InstancePerLifeTimeScope();
builder.Register<IConfigurationService>(c => new ConfigurationService(httpContextBase, new CacheWrapper()).InstancePerLifeTimeScope;
builder.RegisterType<ServiceProxyProvider>().SingleInstance();
builder.RegisterType<wsProfileWrapper>() As <wsProfileWrapper>();
var container = builder.build();
ServiceProxyProvider = container.Resolve<serviceProxyProvider>();
config.DependencyResolver = new AutofacWebAPIDependencyResolver(container);
Log.Trace("Completed Registering dependencies");
}
static void RegisterServiceProxy<T> (ContainerBuilder builder) where T:class
{
builder.Register(_ => _serviceProxyProvider.CreateServiceProxyInstance<T>()).InstancePerRequest()
.OnRelease(x => _serviceProxyProvider.Dispose(x));
}
Thanks.

Hangfire , EF context used in the Task is not updated, the query inside the task always gives the old values

The context used inside the Hangfire task , always gives the old database values, it seems like the context is not updating inside the task. How to get the updated info context data inside hangfire task.
calling the task
BLL.Extraction NewExtractionCls = new BLL.Extraction();
var jobId = BackgroundJob.Enqueue(() => NewExtractionCls.SearchEngineExtraction("SearchURL", "1","1", null));
This is implementation
[Authorize]
public void SearchEngineExtraction(string SearchURL, int PageLimit, int SearchEngineID, PerformContext context)
{
WebClient wc = new WebClient();
#region Main Table - SearchEngineTbl
var NewExtraction = db.SearchEngineTbls.Where(x => x.SearchEngineID == SearchEngineID).FirstOrDefault();
var JobID = context.BackgroundJob.Id;
NewExtraction.JobID = Convert.ToInt32(JobID);
NewExtraction.SeachEngineURL = SearchURL;
NewExtraction.Status = "Processing";
db.SaveChanges();
var LinkCollectionRefined = ExtractLinkFromThisPage(i, SearchURL, wc).Distinct().ToList();//.Skip(10);
foreach (var Link in LinkCollectionRefined)
{
using (Entities dbRefreshed = new Entities())
{
// I get the same old value here, even if I update the table manually, when I rerun, everything is fine.
var CurrentStatusOfExtraction = db.SearchEngineTbls.Where(x => x.SearchEngineID == NewExtraction.SearchEngineID).FirstOrDefault();
if (CurrentStatusOfExtraction.IsActive == false)
{
return;
}
}
}
#endregion
}

RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.

Using Autofac with webapi and mvc5.1 not working for webapi

I have a project using both mvc and webapi.
It's a Membership Reboot application so I have taken the example single application project and have slightly modified it to suit.
The DI works ok for controllers however when I try to call a webapi controller I keep getting an error
Make sure that the controller has a parameterless public constructor.
Is there something else I need to do for using autofac with webapi?
This is the code from my startup.cs
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "External",
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive
});
ConfigureMembershipReboot(app);
}
private static void ConfigureMembershipReboot(IAppBuilder app)
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
//System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<DefaultMembershipRebootDatabase>());
var cookieOptions = new CookieAuthenticationOptions
{
AuthenticationType = MembershipRebootOwinConstants.AuthenticationType
};
BuildAutofacContainer(app, cookieOptions.AuthenticationType);
app.UseMembershipReboot(cookieOptions);
}
private static void BuildAutofacContainer(IAppBuilder app, string authType)
{
var builder = new ContainerBuilder();
var config = CreateMembershipRebootConfiguration(app);
builder.RegisterInstance(config).As<MembershipRebootConfiguration>();
builder.RegisterType<DefaultUserAccountRepository>()
.As<IUserAccountRepository>()
.As<IUserAccountQuery>()
.InstancePerLifetimeScope();
builder.RegisterType<UserAccountService>().OnActivating(e =>
{
var owin = e.Context.Resolve<IOwinContext>();
var debugging = false;
#if DEBUG
debugging = true;
#endif
e.Instance.ConfigureTwoFactorAuthenticationCookies(owin.Environment, debugging);
})
.AsSelf()
.InstancePerLifetimeScope();
builder.Register(ctx =>
{
var owin = ctx.Resolve<IOwinContext>();
return new OwinAuthenticationService(authType, ctx.Resolve<UserAccountService>(), owin.Environment);
})
.As<AuthenticationService>()
.InstancePerLifetimeScope();
builder.Register(ctx=>HttpContext.Current.GetOwinContext()).As<IOwinContext>();
builder.RegisterControllers(typeof(Startup).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
It was a 1 liner :)
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

Use External Css to parse XML

OK i am parsing HTML from a string into a PDFCEll.
It works great thanks to some help from here.
Here is how i am doing it.
How do i use an external css file so i can use class's and not STYLE=""
public class XhtmlToListHelper : IElementHandler
{
// Generic list of elements
public List<IElement> elements = new List<IElement>();
// Add the item to the list
public void Add(IWritable w)
{
if (w is WritableElement)
{
elements.AddRange(((WritableElement)w).Elements());
}
}
string html = "<ul class=\"list\"><li>html 1</li><li>html 2</li><li>html 3</li></ul>";
using (TextReader sr = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(XhtmlHelper, sr);
}
foreach (var element in XhtmlHelper.elements)
{
if (element.IsContent())
{
PDFCell.AddElement(element);
}
}
Now i have got this far, but how to tye it all in evades me. Any help would be much apreacheted.
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/Templates/css/core.css"), true);
If you poke around the source here and you should see how to implement it. Basically, your three line using block quadruples in size and complexity:
var XhtmlHelper = new XhtmlToListHelper();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(#"c:\test.css", true);
var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new ElementHandlerPipeline(XhtmlHelper, null)));//Here's where we add our IElementHandler
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser();
parser.AddListener(worker);
using (TextReader sr = new StringReader(html)) {
parser.Parse(sr);
}